2

I have a method that runs when I call a specific URL on my application. It processes rows in a database queue. The interval is set as lowest interval possible with Cron, ie. 1 minute. This needs dropping to 30 seconds, so I'm wondering how best to achieve this.

I was thinking I could build a loop into my script that runs the code twice, with a sleep of say 30 seconds in between, but I'm wondering if there's a cleaner way than this.

Also, is there a way of running this method from the command line, without the need to call an actual URL?

Chris J Allen
  • 18,970
  • 20
  • 76
  • 114
  • 1
    Or leave your code that way and register a second cronjob that sleeps 30 seconds. Like suggested in [this answer](http://stackoverflow.com/a/9619441/1903366) – lukasgeiter Nov 20 '14 at 14:54
  • this did the job for me, thanks. how would you suggest i answer this question from a comment? – Chris J Allen Nov 20 '14 at 15:02
  • I wrote an answer with an example and pointing out the advantages... – lukasgeiter Nov 20 '14 at 15:14
  • If you are still there, I would like to know how do you call a laravel function from command line. Thank you :) – Sw0ut Feb 23 '16 at 08:25

2 Answers2

4

This answer is strongly inspired by this one

You can leave your code as it is. To call it twice a minute you can add a second cronjob and let one cronjob sleep 30 seconds before executing the task.

* * * * * /path/to/executable param1 param2
* * * * * ( sleep 30 ; /path/to/executable param1 param2 )

This has two advantages

  1. Your code doesn't need to worry about when and how many times it is executed (e.g. if you call it manually it doesn't need to run twice!)

  2. If your code takes 10 seconds to execute everything you would have a delay when using sleep inside of your function. This way you don't.

Community
  • 1
  • 1
lukasgeiter
  • 147,337
  • 26
  • 332
  • 270
1

As in similar threads it was stated, cron is not usable for this, at least not directly. IMHO the most sane approach is to write a shell script, that does your task every 30 seconds, then set up a cron job to check if your script is running, and if not, it should start it.

By the way, a stored procedure would not be a good solution in your case?

meskobalazs
  • 15,741
  • 2
  • 40
  • 63
  • I didn't give enough info initially, but a stored procedure isn't suitable in this case as the script also calls third party APIs and has considerable logic. – Chris J Allen Dec 05 '14 at 14:00