Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

551
Visualizações
Scheduling daily task with node-cron not working

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'
});
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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'
});
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda