Question

I have a webapplication, written in PHP (Zend Framework) and I'd like to execute a (few) script(s) every once in a while. For example once a day. I know this can be done by using crontab and cronjobs, but not all hostingproviders have these available. Therefor I'm looking for a solution without using the Cronjob.

How do you solve this? What are the possibilities?

Was it helpful?

Solution

Cron jobs really only offer a few basic benefits: scheduling, execution and logging. These are all things that are pretty easy to replicate in a PHP application...

Step One: Create a table of tasks

You'd need to store:

  1. Frequency of execution
  2. What to execute (include file, callback, eval code, etc.)
  3. Calculate next run date
  4. Store previous run dates

Step Two: Execution

You have a few options on how to actually trigger the tasks:

  1. Call a PHP-generated blank GIF image on every page run, which triggers the cron code.
  2. Call an AJAX script which runs the cron code
  3. Call it normally inside your application (may slow execution)

No matter how it starts, it would trigger the actual cron code, which decides whether or not there are any tasks to run, and which ones to run.

Step Three: Logging

This one should be pretty simple. Just log what happens during tasks to a file that you can read after to make sure its working.

...

Before running a task, you'd update the previous run date, and after running a task, you'd set the next run date, based on its frequency. The only fallback of this method is that when nobody visits the sites, no cron jobs will execute until the next visitor comes.

OTHER TIPS

You could use an service like this:

CronLess

Configure your script to be accessible from outside, and let this service call the url. For security you could protected the script with some kind of token.

I have done something similar @Adrian Schneider solution. If you want to add more consistency to your app you can add an interface Cronable that forces the classes that implement it to add a cron() function which will handle the internal logic of the cron, that sometimes is different. All this can be wrapped and called in a similar manner by a cron wrapper which will be the only script called by the cron in the system, which will decide what are the current PHP cron jobs to be executed. You can have some more details in my response from here.

I agree with Arne's answer however if you are already using zend framework, you should implement your solution using the built in Zend_Queue which is actually done for that. To see how to implement that here is a link to other question which describes how to set your infrastructure. Infrastructure for Running your Zend Queue Receiver

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top