How to run URL from cronjob at specific time in Linux

Cron allows Linux users to run commands or scripts at a given date and time.

Here I’m going to explain how to setup cron job in Linux in which you want to run URL at specific date-time.

  1. Each user has its own crontab file in Linux. Crontab files can be found in /var/spool folder with file names as username. crontab command is used to add, edit, install, uninstall or list cron jobs.
  2. So to create or edit cron job enter following command:
    crontab –e

Above command will open a crontab file, if exists, otherwise an empty file for creating a new crontab.

  1. Following is syntax for setting cron jobs using crontab file:
    1 2 3 4 5 /path/to/command arg1 arg2

First 5 options are for date-time setup:

    • 1: Minute (0-59)
    • 2: Hours (0-23)
    • 3: Day (0-31)
    • 4: Month (0-12 [12 == December])
    • 5: Day of the week(0-7 [7 or 0 == sunday])
    • /path/to/command – Script or command name to schedule

Example: Following script will run given URLS daily at 2 AM

0 2 * * * curl -s "https://example.com/notification_scirpt?group=1" > /dev/null 2>&1
0 2 * * * curl -s " https://example.com/notification_scirpt?group=2" > /dev/null 2>&1

After adding above lines save file. Command to save a file in VIM editor  iswq!.

Linux will automatically install new crontab changes.

Explaining above code:

  • Above commands will run curl by fetching the URL’s.
  • It will be executed daily at 2 AM.
  • You can also pass query parameters in URL (group in the above example) like normal curl request.
  • –s option is used to make curl silent so that no output generated.

/dev/null and 2>&1 are explained below:

  • > is for redirect
  • /dev/null is a black hole where any data sent, will be discarded
  • 2 is the file descriptor for Standard Error
  • > is for redirect
  • & is the symbol for file descriptor (without it, the following 1 would be considered a filename)
  • 1 is the file descriptor for Standard Out. Therefore >/dev/null 2>&1 is redirecting the output of your program to /dev/null. Include both the Standard Error and Standard Out.

Leave a Reply