Talk To Us For FREE

We are in the Business of Support and that starts before you even become a client.

How to configure cron jobs in Symfony

Categories : Article, Symfony

Many a times, while you are working on a Symfony web development project, you might come across the need to create a scheduled task that runs in the background at a specific time on your web server. This is exactly what a cron job can help you with. Cron jobs are created with the help of a program called crontab on a UNIX/LINUX type web server. Cron jobs very easily automate tasks that you need to run on a regular basis.

Here are the steps to create a cron job:

CREATE A BATCH TASK

Navigate to your project directory and enter the following:

symfony generate:task [example task

This generates a skeleton task on your web server under lib/task/[ example task]Task.class.php.
This essentially contains two important aspects or methods: configure() and extecute().
All the code for the cron job goes in the execute()

CONFIGURATION

There are some configurations that you might want to do before you place all your executable code in the execute(). The following changes will be required in the configure().
$this->namespace = ‘project’;
$this->name = ‘[name-for-example-task]’;
$this->briefDescription = ‘[some short explanation of what example task does]’;

EXECUTION

It’s recommended that you run the code for execution as a Symfony module before setting it up for a cron job only then copy paste it to the execute() method. Now, remember that tasks do not have a visible output, so you will need to echo it in the method. For example:
protected function execute($arguments = array(), $options = array())
{
// initialize the database connection
$databaseManager = new sfDatabaseManager($this->configuration);
$connection = $databaseManager->getDatabase($options[‘connection’] ? $options[‘connection’] : null)->getConnection();

// add your code here

echo “the output here!\n\n”;
}

This completes the cron job configuration and execution requirements now, let’s see how to test it.

NOW RUN IT

Open the commandline and enter the following
symfony project:[example task]
Check whether you see the expected output.

After that’s done, you can open crontab by going to /etc/crontab. This can be opened in a simple text editor. All you need to do is, add this to the end of the document.

*/5 * * * * cd [YOUR SF APP DIR] && /usr/bin/symfony project:[YOUR TASK] >>[YOUR SF APP DIR]/log/crontab.log
This was a very basic explanation. To check the results you can view the log file for crontab at /log/crontab.log .

[Total: 3    Average: 5/5]