根据您在评论中的回复,您正在使用集群。因此,对于每个正在运行的实例,都会创建一个 cron。如果集群中有三个实例,您将获得三个 cron。您需要做的是为您的集群分配一个名称。我会给你一个我们的设置的例子。
这是 ecosystem.config.js 的示例
module.exports = {
apps: [
{
name: 'nest-primary',
script: './dist/src/main.js',
instances: '1',
exec_mode: 'cluster',
time: true,
combine_logs: true,
max_memory_restart: '3500M',
max_old_space_size: 3000,
log_date_format: 'HH:mm YYYY-MM-DD Z',
log_type: 'json',
merge_logs: true,
env_local: {
NODE_ENV: 'local',
HOST: 'localhost',
PORT: 3000,
DATABASE_URL: 'mysql://user:password@localhost:3306/himam',
DATABASE_URL_PG: 'postgresql://postgres:password@localhost:5432/himam',
},
env_development: {
NODE_ENV: 'development',
PORT: 3000,
HOST: '0.0.0.0',
DATABASE_URL: 'mysql://user:password@localhost:3306/himam',
DATABASE_URL_PG: 'postgresql://postgres:password@localhost:5432/himam',
},
},
{
name: 'nest-replica',
script: './dist/src/main.js',
instances: '-1',
exec_mode: 'cluster',
time: true,
combine_logs: true,
max_memory_restart: '3500M',
max_old_space_size: 3000,
log_date_format: 'HH:mm YYYY-MM-DD Z',
log_type: 'json',
merge_logs: true,
env_local: {
NODE_ENV: 'local',
HOST: 'localhost',
PORT: 3000,
DATABASE_URL: 'mysql://user:password@localhost:3306/himam',
DATABASE_URL_PG: 'postgresql://postgres:password@localhost:5432/himam',
},
env_development: {
NODE_ENV: 'development',
PORT: 3000,
HOST: '0.0.0.0',
DATABASE_URL: 'mysql://user:password@localhost:3306/himam',
DATABASE_URL_PG: 'postgresql://postgres:password@localhost:5432/himam',
},
},
当我启动集群时,我通过--env production
pm2 start ecosystem.config.js --env production
最重要的部分,在您的 cron 中,您需要检查实例的名称。您可以通过将您在上面的配置中使用的名称添加到您的 .env 来完成此操作
PM2_PRIMARY_NAME=nest-primary
PM2_REPLICA_NAME=nest-replica
- 最后,在您想要运行 cron 的代码中,检查进程的名称,如下所示:
async handleCron() {
if (process.env.name !== this.configService.get('PM2_PRIMARY_NAME')) {
return;
}
// do your cron logic here.
这确保您的 cron 将只运行一次,因为您的主实例仅在 1 个核心上运行,并且您不会有重复的触发器。请更新我们。