How to create scheduled tasks in Ubuntu for daily / weekly / monthly jobs

Want to run a command or script daily, weekly, monthly, or any other specific schedule? It’s easy to do this on Ubuntu via a cron job.

Cron is a time-based job scheduler that runs commands or scripts on a regular basis at regular times, dates, or intervals. It is typically used to maintain or manage your system, but it is also useful for general purposes, such as downloading files from the Internet on a regular basis.

1. Edit the crontab file.

Users can easily set up cron jobs by configuring the crontab file with the crontab command. It is pre-installed on Ubuntu-based systems. Also, each user has their own crontab configuration file.

b. ) Schedule the current user’s tasks.

To execute a command or script, the current user opens a terminal from the System App Launcher and executes the command.

crontab -e

For the first time, you will be asked to select an editor to edit the configuration file. Select the one you like or press Enter to use the default nano text editor.

b. ) If you need root or sudo privileges:

If the command or script requires sudo or root user privileges, you can run the following command instead.

sudo crontab -e

Create (if not exiting) or open the root user’s configuration file.

c. ) Specify the user who will perform the scheduled task.

You will be added -u <user_name> Flags that specify the user, such as ji.

sudo crontab -u ji -e

The user can be root, so do the same sudo crontab -e:

sudo crontab -u root -e

2. Set the time interval, command, or script to run on a regular basis.

After running the command in step 1, open the configuration file in a terminal window (or command console).

Then scroll down to add a new line.

* * * * * <command or script>

The first five asterisks “*” specify the date and time and change accordingly.

Example:

a. ) For example, to run a python3 script under the My Documents folder every Sunday at midnight (00:00), use:

0 0 * * 0 python3 /home/ji/Documents/script.py

Here:

  • The first 0 specifies the minute and uses * every minute.
  • The second 0 specifies the time, using * every hour.
  • The third flag * specifies the day of the week. Every day if no day of the week is specified.
  • The fourth flag * says every month.
  • The fifth flag (third 0) specifies the day of the week. 0 to 6 means Sunday to Saturday.

b. ) Run echo "hello world!" Run the command every day at 16:30 and add the following line:

30 16 * * * echo "hello world!"

c. ) Can be used */n Executes every nth time interval. Also, use commas to use multiple specific time intervals.

For example, run the command every 5 minutes every 1, 2 or 3 hours every Friday (01:00, 01:05, 01:10, …, 02:00, 02:05, 02:10, … , 03:55).

*/5 1,2,3 * * 5 echo "hello world!"

Finally, save the configuration file. When editing with nano, press Ctrl + X on your keyboard, type y, and press Enter to save.

Share this:

  • More

Related Posts