msavin / SteveJobs

A simple jobs queue that just works (for Meteor.js)
Other
207 stars 35 forks source link

Run job every day at same time #71

Closed thcdevcl closed 4 years ago

thcdevcl commented 5 years ago

Hello!

I need to schedule a job that runs ever day at same time and I am not getting how to do it. So please I am asking for your help!

Cheers!

msavin commented 5 years ago

Hey @noincomedev

First, you need to register your job:

Jobs.register({
    "syncData": function () {
        var instance = this;

        var call = HTTP.put("http://www.magic.com/syncData")

        if (call.statusCode === 200) {
            instance.replicate({
                in: {
                    hours: 24
                }
            });

            // alternatively, you can use instance.remove to save storage
            instance.success(call.result);
        } else {
            instance.reschedule({
                in: {
                    minutes: 5
                }
            });
        }
    }
});

Notice how the job replicates itself to run 24 hours after it has been executed.

Then, you need to "kickstart" it by getting the first job going:

Meteor.startup(function () {
    Jobs.run("syncData", {
        on: {
            hours: 23,
            minutes: 55,
            seconds: 0,
            milliseconds: 0
        }
        singular: true
    })    
})

It will use the timezone on your server and run the job at the time you specified. The singular flag will ensure that a new job is not created if there is one already pending (or failed).

msavin commented 5 years ago

There are two areas where you might have issues:

First, the queue does not run on exact time, as it currently runs on a polling mechanism. Thus, you could expect a bit of deviation. This could be adjusted, but I haven't had the time yet.

Second, when you reschedule a job, it will reschedule from the current time, and not the time of the job. However, you can change that by passing in the "base" time.

For example:

Jobs.register({
    "syncData": function () {
        var instance = this;
        var originalDueTime = this.document.due

        // ...
            instance.replicate({
                in: {
                    hours: 24
                },
                date: originalDueTime
            });

        // ...
    }
});
thcdevcl commented 5 years ago

Thanks you so much for your detailed answer! Will try it out and get you the outcome!