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

286
Visualizações
How to export a variable from a scheduled function

I have a function that gets input constantly but then only processes it every minute with a cron job.

The most recent output should be stored in a variable and retrieved from the outside at random times.

Here in a very simplified form:

let input = 'something';

let data = '';
data += input;

require('node-schedule').scheduleJob('* * * * *', somethingMore);

function somethingMore() {
let output = data += 'More';
// return output;
}

console.log(output);

Initializing the variable outside the function like above doesn't seem to work in this case.

Calling the function directly or assigning it to a variable doesn't help, as it would run it before it's due.

I also tried with buffers, but they don't seem to work either, unless I missed something.

The only thing that does work is writing a file to disk with fs and then reading from there, but I guess it's not the best of solutions.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

It seems like you just let your chron function run as scheduled and you save the latest result in a module-scoped variable. Then, create another exported function that anyone else can call to get the latest result.

You're only showing pseudo-code (not your real code) so it is not clear exactly what you want to save for future inquiries to return. You will have to implement that part yourself.

So, if you just wanted to save the most recent value:

// module-scoped variable to save recent data
// you may want to call your function to initialize it when
// the module loads, otherwise it may be undefined for a little bit
// of time
let lastData;

require('node-schedule').scheduleJob('* * * * * *', () => {
     // do something that gets someData
     lastData = someData;
});

// let outside caller get the most recent data
module.exports.getLastData = function() {
    return lastData;
}
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