Strapi 的 CRON 示例

CRON Example for Strapi

你好,我想知道是否有人得到了在 Strapi 上使用 Cron Schedule 函数的示例:https://strapi.io/documentation/3.x.x/configurations/configurations.html#functions 比如发送电子邮件、访问 strapi 配置等

'*/1 * * * *': async() => {
    console.log("I am running " + new Date(), Object.keys(strapi.config));
    await strapi.services.article.publish();
  }

your-project/config/functions/cron.js。您可以按上述格式添加尽可能多的功能。 函数名称本身是一个 cron 表达式,由 strapi 解析以频繁执行。有许多在线工具会告诉您要创建的 cron 表达式。

上述函数每 1 分钟运行一次,我使用 strapi.services 发布了一个内容类型。即在文件 your-project/api/article/services/Article.js 自己写了一个服务层的方法,目前正在发文

同样,您可以从您的电子邮件内容类型或您创建的用于触发电子邮件的任何实用程序文件发送电子邮件。 要访问 strapi 配置,请使用:strapi.config 对象而不是 strapi.services

Strapi 3 默认关闭 cron 作业。确保先打开它们:)

您也不需要在 cron 作业中每分钟都执行 */1,只需 *,因为 * 表示每个,而且它每分钟只检查一次。

我的要求是从托管在 RDS (AWS) 下的外部 MSSQL 数据库(主数据)中获取数据,并每分钟更新一次 strapi 产品目录 (mongodb)。

我在 "root" 下创建了一个自定义 "cron" 文件夹来保存我所有的自定义模块,以便保持干净 "cron.js"。

在 "cron.js" 下,我只是导入了我的自定义模块来调用外部模块:

const fwSync = require('../../cron/dataSync');

Strapi 的一些 CRON 作业示例

添加这一行server.js

...
  port: env.int('PORT', 1337),
  cron :{
    enabled: true
  },
  admin:
...

cron.js 一些例子

module.exports = {
  /**
   * Simple examples.
   */
  '*/5 * * * * *': () => {
    console.log(" ~ file: cron.js ~ executing action ~Every 5sec");
  },  
  '*/10 * * * * *': () => {
    console.log(" ~ file: cron.js ~ executing action ~Every 10sec");
  },
  '* */5 * * * *': () => {
    console.log(" ~ file: cron.js ~ executing action ~Every 5min");
  },
  '* * */5 * * *': () => {
    console.log(" ~ file: cron.js ~ executing action ~Every 5hour");
  },   
};