cron snippets

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

Tagged cakephp, cron, job  Languages php

First copy webroot/index.php to webroot/cron_scheduler.php. Replace everything below require CORE_PATH . 'cake' . DS . 'bootstrap.php'; with the following code:

# This was added to webroot/cron_scheduler.php

# Check that URI was specified and that we're called from the command line (not the web)
if($argc == 2 && php_sapi_name() === "cli") 
    # Set request URI
    $_SERVER['REQUEST_URI'] = $argv[1];
    # Set user-agent, so we can do custom processing
    $_SERVER['HTTP_USER_AGENT'] = 'cron';
    $Dispatcher= new Dispatcher();


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

$ php cron_scheduler.php /controller/action

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

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

Scheduling jobs to run daily, weekly or monthly with Cron

Tagged cron, scheduling, daily, weekly, monthly  Languages bash

Cron syntax and valid values:

# +---------------- minute (0 - 59)
# |  +------------- hour (0 - 23)
# |  |  +---------- day of month (1 - 31)
# |  |  |  +------- month (1 - 12)
# |  |  |  |  +---- day of week (0 - 6) (Sunday=0 or 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):

# Every 10 minutes
*/10 * * * * /home/belsebub/

# Every 30 minutes
*/30 * * * * /home/belsebub/

# Every 60 minutes
*/60 * * * * /home/belsebub/

# Every day at 00:00
00 00 * * * /home/belsebub/

# Every saturday at 00:00
00 00 * * 6 /home/belsebub/

# First day of every month at 00:00
00 00 1 * * /home/belsebub/

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

Running (and debugging) cronjobs with rbenv and bundler

Tagged rbenv, backup, cron, bundler  Languages bash

This snippet shows how to run a backup script (Backup gem) and how to debug cron in case it doesn't work.

This example uses bundler and rbenv to complicate things:

# Set the path to include rbenv

# Debug cron environment...
*/1 * * * * /bin/bash -l -c '/bin/env > /tmp/cron-env.log'

# Run backup every 12 hours
* */12 * * * /bin/bash -l -c 'eval "$(rbenv init -)" && cd /var/www/xxx/current && bundle exec backup perform --trigger xxx -c config/backup.rb >> /tmp/backup.log 2>&1'

If backup fails, check /tmp/backup.log and/or /tmp/cron-env.log.

How to parse a cronline/crontab/cron with Ruby

Tagged cron, cronline, ruby  Languages ruby

You can use the rufus-scheduler gem to parse cronline/crontab/cron with Ruby.


gem 'rufus-scheduler'


require 'rufus/scheduler/cronline'
cron ="00 00 1 * *") # 00:00 every first day of the month
next_time = cron.next_time(Time.current)
previous_time = cron.previous_time(Time.current)

rufus-scheduler's cronline implementation:

See tests for details and syntax:

Cron configuration examples.

How to get notified when a Cron job fails

Tagged cron, alert, notify  Languages 

To get notified when a cron script fails you can tell cron to send any errors to you by email.

It already does this by default, but the emails are sent to the Unix account's mailbox:

cat /var/spool/mail/<username> | less

To use a different email address use the MAILTO setting as described here:

[email protected]
0 */2 * * * /bin/ > /dev/null

Cron will now send an email whenever the script (/bin/ prints something to stderr.

If the script is printing to stderr without it failing try Cronic:

0 */2 * * * cronic /bin/

You can of course also try to fix the script by not printing to STDERR unless it's really an error.

Check the mail log to see if it's working:

sudo tail -f /var/log/mail.log

If you're email server is rejecting emails sent by cron you might need to set the MAILFROM variable. However, only some cron version supports MAILFROM.

Testing Whenever with Rspec

Tagged cron, rspec, whenever  Languages ruby
require 'spec_helper'
require 'whenever'

describe Whenever do
  def gen_cron(stage:)
    x =
      file: Rails.root.join("config", "schedule.rb").to_s,
      set: "stage=#{stage}"
    x.gsub(Dir.pwd, "")

  it "generates correct cron configuration for each stage" do
    [ :qa, :production ].each do |stage|
      expected ="spec/fixtures/#{stage}.cron")
      cron = gen_cron(stage: stage)
      # NOTE: Uncomment to update expected cron configuration"spec/fixtures/#{stage}.cron", "w") {|x| x << cron }
      assert_equal expected.strip, cron.strip

Notifications for failing cron jobs

Tagged cron, failure, notification, slack  Languages bash

Here’s a simple way of receiving a notification to a Slack channel when a cron job fails:

#!/usr/bin/env sh

# Replace this with the command
echo "hello world" &> /var/log/app.log

if [ $? -eq 0 ]
  curl -X POST -H 'Content-Type: application/json' --data "{\"text\":\"Cron job ran successfully $(tail -n 5 /var/log/app.log)\"}" $SLACK_URL
  exit 0
  curl -X POST -H 'Content-Type: application/json' --data "{\"text\":\"Cron job failed $(tail -n 5 /var/log/app.log)\"}" $SLACK_URL
  exit 1

Set the SLACK_URL environment variable to your slack channel’s hook URL.

A message will be sent to the Slack channel whenever the command fails along with the last 5 lines from the log file.

How to set the environment variables in a cron script (Docker)

Tagged cron, docker, env, crontab, environment, docker-compose  Languages bash

To give your cron script access to the same environment variables as the Docker container, you can read and export the environment variables for the PID 1 process in your script:

crontab -l
* * * * * /app/


#!/usr/bin/env bash
# Read the environment variables for the main process (PID 1) running in the Docker container:
export $(xargs -0 -a "/proc/1/environ")

python3 -m $1

How to get cron to log to STDOUT under Docker and Kubernetes

Tagged cron, dockerfile, pid, stderr, stdout  Languages bash


FROM python:3.9-slim-buster
COMMAND ["cron", "-f"]

By running cron as PID 1 the output is redirected to the file descriptor of PID.

To write the output from cron jobs to PID 1, you can try to redirect the output like this:

# Redirects both stderr and stdout to stdout of PID 1: &>> /proc/1/fd/1
# Redirects stderr and stdout to stdout and stderr of PID 1: 1>> /proc/1/fd/1 2>> /proc/1/fd/2

Each PID (process) has it’s own file descriptors:

/proc/{PID}/fd/0 # STDIN
/proc/{PID}/fd/1 # STDOUT
/proc/{PID}/fd/2 # STDERR