安排日常任务使用节点克朗不起作用

发布于 2025-02-04 14:28:07 字数 593 浏览 1 评论 0原文

我正在尝试创建一个返回当天随机歌曲的API。我试图安排随机功能每天运行一次,以选择当天的新歌。我正在使用Node-Cron来做到这一点。但是,此功能每天不止一次运行。它的运行似乎更像一个小时,但是我不确定它的运行频率。如果有任何区别,则API将在Heroku上托管。

const cron = require('node-cron');

let usedSongs = [];
let use;

function randomize() {
    if(usedSongs.length === 169) {
        usedSongs = [];
    };
    let test = Math.round(Math.random(0,1) * 169);
    usedSongs.includes(test) ? randomize() : use = String(test);
    usedSongs.push(test)
};
randomize();

cron.schedule('0 0 0 * * *', () => {
    randomize();
}, {scheduled: true,
    timezone: 'America/New_York'
});

I'm trying to create an api that returns a random song of the day. I'm trying to schedule the randomize function to run once a day to pick a new song for that day. I'm using node-cron to do this. This function is running way more than once a day, however. It appears to be running more like once an hour, but I'm not certain how often its running. The api is hosted on Heroku if that makes any difference.

const cron = require('node-cron');

let usedSongs = [];
let use;

function randomize() {
    if(usedSongs.length === 169) {
        usedSongs = [];
    };
    let test = Math.round(Math.random(0,1) * 169);
    usedSongs.includes(test) ? randomize() : use = String(test);
    usedSongs.push(test)
};
randomize();

cron.schedule('0 0 0 * * *', () => {
    randomize();
}, {scheduled: true,
    timezone: 'America/New_York'
});

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

混浊又暗下来 2025-02-11 14:28:07

您似乎两次调用Randomize() - 仅在方法定义之后(可能每次服务器启动时(?)和在调度程序内再次运行),哪个应该按预期发射一次。

function randomize() {
    if(usedSongs.length === 169) {
        usedSongs = [];
    };
    let test = Math.round(Math.random(0,1) * 169);
    usedSongs.includes(test) ? randomize() : use = String(test);
    usedSongs.push(test)
};
randomize();    <<<<<<<<<<<<<<<<<<

cron.schedule('0 0 0 * * *', () => {
    randomize();     <<<<<<<<<<<<<<<<<
}, {scheduled: true,
    timezone: 'America/New_York'
});

You appear to be calling randomize() twice - once just after the method definition (which will run probably every time the server starts(?), and again inside the scheduler - which should fire once per day as expected.

function randomize() {
    if(usedSongs.length === 169) {
        usedSongs = [];
    };
    let test = Math.round(Math.random(0,1) * 169);
    usedSongs.includes(test) ? randomize() : use = String(test);
    usedSongs.push(test)
};
randomize();    <<<<<<<<<<<<<<<<<<

cron.schedule('0 0 0 * * *', () => {
    randomize();     <<<<<<<<<<<<<<<<<
}, {scheduled: true,
    timezone: 'America/New_York'
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文