Eurydice
Eurydice

Reputation: 8419

refresh page periodically and programmatically

I have an angular application for which I would like to refresh the page periodically say everyday at 12PM. To do so, I want to use the cron library which in principle should do the job. My cron implementation is the following:

import { CronJob } from 'cron';

const cron: CronJob = new CronJob('* * * * * *', () => {window.location.reload()}, null,true);
cron.start();

My problem is where to put that code. If I put it in a component then the cron will be restarted each time the component will be reloaded which should be avoided. The problem will be the same with a service that would be injected in a component. So where can I put my cron so that it is declared just once for all ? Would you have any idea ?

Upvotes: 0

Views: 304

Answers (1)

Edward
Edward

Reputation: 1126

I would recommend avoiding reloading the entire app every few minutes to avoid the bootstrapping process involved with every reload. Preferably, use a Service to reload the specific components you want to periodically update.

That being said, if you are intent on reloading the entire app with this approach, you can either

  • Create an @Injectable() service, making sure to use provideIn: root, and have the service injected into the app.component. this will ensure your service is initialized only once.
    • More here on Angular Services
    • place your cron logic in the constructor of the service.
  • or you can simply place this logic directly in the root app component

Upvotes: 2

Related Questions