Call a server method with a Cron

Hello,

I’m finishing my meteor App and there is one thing I still don’t know how to implement.

I have a server method that should run every X minutes, i wonder if there is a way to set up a url that calls to this method and afterwards configure a cron calling to this url every X minutes.

Do you have any suggestions on this?

Thanks!

How about a server route with iron:router?

Hello Dave,

I’ve been checking the documentation for this: https://github.com/iron-meteor/iron-router/blob/devel/Guide.md#creating-routes

But I don’t really understand how to apply this with my code.

Router.route('/cron', function () {
//should I write here my server-side code?
}, {where: 'server'});

So when I call “http://www.myapp.com/cron” the code will run?

As far as I know, yes the code should run! But be warned, anyone will be able to access that route, so some kind of auth should be done on the server, co only the cron can run it :wink:

hey @poliuk

two different suggestions:

  1. meteor package: https://github.com/percolatestudio/meteor-synced-cron
  2. npm package: https://www.npmjs.com/package/ddp

the first would let you schedule jobs within your project scope, which means all functionality is available!

the second would let you make remote calls from outside your project (which is suitable for writing small nodejs scripts run by cron)

I personally haven’t used either yet, but I’m about to soon (just procrastinating this task :slight_smile: )

1 Like

I’m gonna try this :smile:

It’s a cron that has to run every minute, so it is not a problem if anyone access to that url

I’m going to try this one too, thanks!!

Well at the end it was pretty easy using iron router. I share the code in case anyone step upon this post in the future:

Router.route('/closePromos',function(){
     //server side code here
       
            ...
      
     var res = this.reponse;
     res.end('Your server has executed the code');
}, {where : 'server' });

Then you just have to set up a cron with a curl to the /closePromos route. It is important to do the reponse.end() :wink:

If someone makes 1000 calls to that url in that minute, it won’t cause any issues?

1 Like

You are completely right, it will be better to create a “password” system, I think I can use the request object to do so.

Thanks!

I would still do it using synced cron, some example

SyncedCron.add({
  name: 'whatever u want dude',
  schedule: function(parser) {
    // parser is a later.parse object
    return parser.text('every 5 minutes');
  },
  job: function() {
    serverFunctionToCall();
    return true;
  }
});
1 Like