3

I have created a background job like this:

Parse.Cloud.job("ResetLeaderboard",
    function(request, response)
    {
        Parse.Cloud.useMasterKey();

        var query = new Parse.Query("Leaderboard");

        query.find(
            {
                success: function(results)
                {
                    response.success("Success!");
                },

                error: function(error)
                {
                    response.error(error);
                }
            })
            .then(
                function(results)
                {
                    return Parse.Object.destroyAll(results);
                });
    });

I want to run this job every 15 days. But there is no option available at www.parse.com to set time interval for more than a day.

I think I need to use a time stamp and compare that value with current time. Can somebody show me the standard way to do this?

Ehtesham Hasan
  • 4,133
  • 2
  • 23
  • 31

1 Answers1

2

You're right that the job scheduling UI is constrained to a single day. The way to solve the problem is to have the job run daily, but to have it do nothing on 14 out of 15 runs. Those do-nothing runs will be wasteful, but microscopically so, and parse is paying the bills anyway.

The specifics of the solution depend on specific requirements. If you require maximum control, like exactly 15 days down to the millisecond, starting at a millisecond-specific time, you'd need to create some scratch space in the database where state (in particular, date) from the prior run is kept.

But the job looks like a cleanup task, where the requirement of "very nearly 15 days, beginning within 15 days" is sufficient. With that simpler requirement, your intuition is correct that simple date arithmetic will work.

Also, importantly, it looks to me like your intention is to find several objects in need of deletion, then delete them. The posted logic doesn't quite do that. I've repaired the logic error and cleaned up the promise handling as well...

// Schedule this to run daily using the web UI
Parse.Cloud.job("ResetLeaderboard", function(request, response) {
    if (dayOfYear() % 15 === 0) {
        var query = new Parse.Query("Leaderboard");
        query.find().then(function(results) {
            Parse.Cloud.useMasterKey();
            return Parse.Object.destroyAll(results);
        }).then(function() {
            response.success("Success!");
        }, function(error) {
            response.error(error);
        });
    } else {
        response.success("Successfully did nothing");
    }   
});

function dayOfYear() {
    var now = new Date();
    var start = new Date(now.getFullYear(), 0, 0);
    var diff = now - start;
    var oneDay = 1000 * 60 * 60 * 24;
    return Math.floor(diff / oneDay);
}

The dayOfYear function is thanks to Alex Turpin, here

Community
  • 1
  • 1
danh
  • 62,181
  • 10
  • 95
  • 136