Manage cron tasks commands without relying on system operators
$ composer require trovit/cron-manager-bundle "~0.1"
<?php
// app/AppKernel.php
public function registerBundles()
{
$bundles = array(
// ...
new Trovit\CronManagerBundle\TrovitCronManagerBundle(),
// ...
);
}
$ php bin/console doctrine:schema:update --force
<?php
//...
$this->get('trovit.cron_manager.create_cron_task')->create(
$name = 'CronTask Example',
$description = 'Example cron task',
$command = 'cache:clear',
$interval = 'PT1H' // DateInterval format: http://php.net/manual/en/dateinterval.construct.php
);
//...
There are two ways to execute the cron manager: via a cronjob or via system daemon. Important: the cron must be executed every minute to work properly.
Add this line into your crontab file:
*/1 * * * * php /path/to/your/project/app/console cron:execute --no-debug >/dev/null 2>&1
You could use Upstart. If you do so, create a file named cron-manager.conf and place it in /etc/init.d:
description "Cron tasks manager runner"
author "Trovit"
# Tell Upstart to respawn our command on a crash
# stop restarting if it crashes more then 5 times within 10 seconds
respawn
respawn limit 5 10
# Tell Upstart to start us after MySQL started and shut us down on system shutdown
start on started mysql
stop on runlevel S
# Run as the www-data user and group
setuid www-data
setgid www-data
exec php /path/to/your/project/app/console cron:execute --daemon --no-debug >/dev/null 2>&1
To start the daemon, execute start cron-manager
.
<?php
//...
$cronTask = $this->getDoctrine()->getRepository('TrovitCronManagerBundle:TblCronTask')->find($id);
$this->get('trovit.cron_manager.update_cron_task')->update(
$cronTask,
$name = 'CronTask Example updated',
$description = 'Example cron task updated',
$command = 'cache:clear --no-warmup',
$interval = 'PT30M' // DateInterval format: http://php.net/manual/en/dateinterval.construct.php
);
$this->get('trovit.cron_manager.update_cron_task')->deactivate($cronTask);
$this->get('trovit.cron_manager.update_cron_task')->activate($cronTask);
//...
<?php
//...
$cronTask = $this->getDoctrine()->getRepository('TrovitCronManagerBundle:TblCronTask')->find($id);
$this->get('trovit.cron_manager.delete_cron_task')->delete($cronTask);
// It can also be deleted by id
// $this->get('trovit.cron_manager.delete_cron_task')->deleteById($id);
//...
<?php
//...
$allCronTasks = $this->get('trovit.cron_manager.read_cron_task')->getAllCronTasks();
$activeCronTasks = $this->get('trovit.cron_manager.read_cron_task')->getActiveCronTasks();
//...