Register now and start sharing your code snippets.

Scheduling jobs to run daily, weekly or monthly with Cron

Shell Script (Bash) posted 6 months ago by christian

Cron syntax and valid values:

   1  # +---------------- minute (0 - 59)
   2  # |  +------------- hour (0 - 23)
   3  # |  |  +---------- day of month (1 - 31)
   4  # |  |  |  +------- month (1 - 12)
   5  # |  |  |  |  +---- day of week (0 - 6) (Sunday=0 or 7)
   6  # |  |  |  |  |
   7    *  *  *  *  *  command to be executed

Below are a few examples on how to run a script every 10 minutes, every 30 minutes, every hour, daily, weekly, monthly.

Execute crontab -e and add the following (see man crontab):

   1  # Every 10 minutes
   2  */10 * * * * /home/belsebub/delete_old_stuff.sh
   3  
   4  # Every 30 minutes
   5  */30 * * * * /home/belsebub/delete_old_stuff.sh
   6  
   7  # Every 60 minutes
   8  */60 * * * * /home/belsebub/delete_old_stuff.sh
   9  
  10  # Every day at 00:00
  11  00 00 * * * /home/belsebub/delete_old_stuff.sh
  12  
  13  # Every saturday at 00:00
  14  00 00 * * 6 /home/belsebub/delete_old_stuff.sh
  15  
  16  # First day of every month at 00:00
  17  00 00 1 * * /home/belsebub/delete_old_stuff.sh

On Debian the configuration goes to /var/spool/cron/crontabs/username.

Tagged cron, scheduling, daily, weekly, monthly

How to execute a CakePHP controller's action from a cron job

PHP posted 6 months ago by christian

First copy webroot/index.php to webroot/cron_scheduler.php. Replace everything below require CORE _PATH . ‘cake’ . DS . ‘bootstrap.php’; with the following code:

   1  #
   2  # BEGIN
   3  #
   4  # This was added to webroot/cron_scheduler.php
   5  #
   6  
   7  # Check that URI was specified and that we're called from the command line (not the web)
   8  if($argc == 2 && php_sapi_name() === "cli") 
   9  {
  10  	# Set request URI
  11  	$_SERVER['REQUEST_URI'] = $argv[1];
  12  	# Set user-agent, so we can do custom processing
  13  	$_SERVER['HTTP_USER_AGENT'] = 'cron';
  14  	
  15  	$Dispatcher= new Dispatcher();
  16  	$Dispatcher->dispatch($argv[1]);
  17  } 
  18  
  19  #
  20  # END
  21  #
  22  # 
  23  #

Now you can execute CakePHP from the command line with the following command:

   1  $ php cron_scheduler.php /controller/action

If you get the following error, remove the lines containing line feeds in bootstrap.php:

   1  Warning: Cannot modify header information - headers already sent by (output started at .../app/config/b
   2  ootstrap.php:48) in .../app/app_controller.php on line 46

Tagged cakephp, cron, job