How to create a cron job in Linux

Balvinder Singh
Tekraze
Published in
3 min readApr 9, 2020

Cron Job is the job done by system cron every day or like timed, for a specific set of operations and processes like cleaning up, maintenance and more.

So If you have some process like cleaning up of logs every 7 days, or deleting files older than 7 days, or like clearing the cache. You can do with cron job.

let us see how can we do with an example of file deletion or directory deletion.

  1. Open a terminal and enter the command below
crontab -e

it will open up the cron file for a user, where we can write the commands.

Note : For creating root user cron, do use sudo or sudo su before

2. If there are no cron jobs previously setup, a new file needs to be created. So you will be asked of the editor. Choose nano as the preferred option.

3. With nano editor opened. Do write the below code

# skip if the cron already have these
# this line ensures user is using the shell and bin while commands are executed
SHELL=/bin/sh
PATH=/etc:/bin:/sbin:/usr/bin:/usr/sbin
# Order of crontab fields for writing
# minute hour mday month wday command
# TO remove a folder/directory somewhere# TO run after each minute
*
* * * * find /home/user/some-folder/* -type d -delete
# To run Daily
@daily find /home/user/some-folder/* -type d -delete
# TO remove a file/files somewhere# TO run after each minute
*
* * * * find /home/user/some-folder/* -type f -delete
# To run Daily
@daily find /home/user/some-folder/* -type f -delete

4. Ctrl + X to save or other combinations for your opened editor.

you will see the installed message, which means cron job is fine.

you can verify the cron job by setting the one minute time and see, then set back a different time.

5. You have successfully configured a crontab job. You can add your command in place of these to setup.

Note: commands are simple shell commands

Timing parameters can be set from below.

           string	   meaning
------ -------
@reboot Run once, at startup of cron.
@yearly Run once a year, "0 0 1 1 *".
@annually (same as @yearly)
@monthly Run once a month, "0 0 1 * *".
@weekly Run once a week, "0 0 * * 0".
@daily Run once a day, "0 0 * * *".
@midnight (same as @daily)
@hourly Run once an hour, "0 * * * *".
@every_minute Run once a minute, "*/1 * * * *".
@every_second Run once a second.

for more reference check Link

Do let us know in the comments below if this helped you. Do clap to show support for us.

Also, follow our Blog for more articles.

--

--

Balvinder Singh
Tekraze

Open Source FullStack Developer | Blogger | Crypto Enthusiast | Gamer