Automate tasks with init and cron

December 2016




Under Linux, you can easily automate tasks with the init command, to start a task at startup, or with cron to run a task at a time.
There are several software managing cron, here we will get a good preview of on of these software: crontab.

Create a new task


First of all, we must create a new file that will execute the code that you want.
To do this, simply open an editor (as root), and save the file in the folder you want. Make sure to include the interpreter used at the beginning of the file.
For example (using bash):
#!/bin/bash 
command;

...
It is possible to use another shell, simply by changing #!/bin/bash chosen by the interpreter: #!/bin/python, #!/bin/perl, etc..

Then we must make the file executable:
# chmod 755 /directory/myfile

Automate a task at startup: init


Overview

init is the first process executed by the kernel.
At startup, it runs various scripts in /etc/init.d/ or /etc/rc*.d/.
In the /etc/init.d you must save the file to launch at startup.
You must then add the file to the list of processes running at startup:
# update-rc.d my-fil3 defaults

For more information


Type in a terminal:
  • ls -l /etc/init.d/: to see scripts running at startup
  • init --help
  • cat /etc/init.d/README
  • man init
  • info init
  • man update-rc.d

Start a task at a specific time: crontab


Overview
  • cron can run a task periodically: daily, weekly, every hour ...
    • There is a cron file for user

Adding a task


There are several folders containing tasks performed by cron:
  • /etc/cron.hourly : run scripts each hour.
  • /etc/cron.daily : scripts executed each day. .
  • /etc/cron.weekly : run scripts each week.
  • /etc/cron.monthly: run scripts each month.


Simply create a file in the folder.

However, it is possible to try to initiate tasks at more accurate times.
For this, we must create a file with correct syntax for crontab in /etc/cron.d, which contains a command or execute another file.


It is also possible to create tasks for a particular user. You must edit the crontab of the user.

Syntax for crontab


There are already many tutorials on the web about it.

Start a task for a sole user


To do this, edit the file name by typing in a console crontab-e.
If you want to create a crontab file for another user then you must go through the command
  • # crontab -u user -e.   
    • You must then save the file without changing its name or location.
    • You will always go through the command crontab-e to edit the file.

For more information


Type in a terminal:

Cron with GUI


There are various graphics software that can create automated tasks:
  • kcron  
  • gcrontab

Related :

This document entitled « Automate tasks with init and cron » from CCM (ccm.net) is made available under the Creative Commons license. You can copy, modify copies of this page, under the conditions stipulated by the license, as this note appears clearly.