cron-tasks.ts 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. module.exports = {
  2. checkPublish: {
  3. task: async ({ strapi }: { strapi: any }) => {
  4. try {
  5. // Safety check: verify the content type exists before proceeding
  6. if (!strapi.contentTypes['api::blog.blog']) {
  7. console.log('Blog content type not found. Skipping scheduled publish task.');
  8. return;
  9. }
  10. const now = new Date();
  11. console.log('[Cron] Checking for scheduled blog posts to publish at:', now.toISOString());
  12. try {
  13. const drafts = await strapi.documents('api::blog.blog').findMany({
  14. filters: {
  15. publish_at: { $lte: now },
  16. auto_publish: true
  17. },
  18. status: 'draft',
  19. });
  20. console.log(`[Cron] Found ${drafts?.length || 0} blog posts to publish`);
  21. for (const draft of drafts) {
  22. try {
  23. console.log('[Cron] Publishing entry:', draft.documentId);
  24. // Update the auto_publish flag first
  25. await strapi.documents('api::blog.blog').update({
  26. documentId: draft.documentId,
  27. data: { auto_publish: false },
  28. status: 'draft',
  29. });
  30. // Then publish the blog post
  31. await strapi.documents('api::blog.blog').publish({
  32. documentId: draft.documentId,
  33. });
  34. console.log('[Cron] Successfully published blog post:', draft.documentId);
  35. } catch (postError) {
  36. console.error(`[Cron] Error publishing blog post ${draft.documentId}:`, postError);
  37. // Continue with next post even if one fails
  38. }
  39. }
  40. } catch (queryError) {
  41. console.error('[Cron] Error querying drafts:', queryError);
  42. }
  43. } catch (error) {
  44. console.error('[Cron] Uncaught error in checkPublish task:', error);
  45. }
  46. },
  47. options: {
  48. rule: '*/10 * * * *', // Run every 10 minutes
  49. },
  50. },
  51. };