In A cron basics we learned how to set up a cron job in a local environment. Today I am going to show you how to set it programmatically using Vagrant.

Provisioning files

A script file

First, we write a script we want to execute. To make it as simple as possible we just write current date to a /vagrant/www/cron.html file

#!/usr/bin/env bash

# File: vagrant/cron/cron-job.sh

# Write current date to cron.html
echo $(date) > /vagrant/www/cron.html

Crontab file

Secondly, we define a crontab file.

# Run example cron job
*/1 * * * * bash /vagrant/vagrant/cron/cron-job.sh

# Comment to make sure there is new line at the end of file
# https://askubuntu.com/questions/23009/why-crontab-scripts-are-not-working/23337#23337

Do you know how often will be this script executed? No? Go check the Online Crontab Editor.

Installation

Finally, we install new crontab file.

#!/usr/bin/env bash

# File: vagrant/cron/cron.sh

echo "----- Provision: Setting up cron ..."
# Overwrite crontab configuration
crontab /vagrant/vagrant/cron/crontab

And we update master unprivileged script because we do not need a privileged user for that.

#!/usr/bin/env bash

# File: vagrant/unprivileged.sh

# ...
# Available unprivileged configurations
bash /vagrant/vagrant/cron/cron.sh
# ...

Does it work?

To see if it works visit http://project.v.martinvana.com/cron.html.


Sources