10 Cron Scheduling Task Examples in Linux

10 Cron Scheduling Task Examples in Linux

As a Linux user, you may have already heard of cron. Cron is a time-based job scheduler in Unix/Linux operating systems that allows you to schedule commands or scripts to automate tasks at specified intervals, such as daily, weekly, or monthly. In this article, we will cover 10 examples of cron scheduling tasks in Linux.

Example 1: Running a Script Twice a Day

To run a script twice a day, you can use the following cron command:

0 8,20 * * * /path/to/script.sh

This means that the script will run every day at 8:00 AM and 8:00 PM.

Example 2: Running a Script Every Minute

To run a script every minute, you can use the following cron command:

* * * * * /path/to/script.sh

This means that the script will run every minute.

Example 3: Running a Script Every Hour

To run a script every hour, you can use the following cron command:

0 * * * * /path/to/script.sh

This means that the script will run on the hour every hour.

Example 4: Running a Script Every Day

To run a script every day, you can use the following cron command:

0 0 * * * /path/to/script.sh

This means that the script will run every day at midnight.

Example 5: Running a Script Every Week

To run a script every week, you can use the following cron command:

0 0 * * 0 /path/to/script.sh

This means that the script will run every Sunday at midnight.

Example 6: Running a Script Every Month

To run a script every month, you can use the following cron command:

0 0 1 * * /path/to/script.sh

This means that the script will run on the first day of every month at midnight.

Example 7: Running a Script Every Year

To run a script every year, you can use the following cron command:

0 0 1 1 * /path/to/script.sh

This means that the script will run on January 1st of every year at midnight.

Example 8: Redirecting Output to a Log File

To redirect the output of your cron task to a log file, you can use the following command:

* * * * * /path/to/script.sh >> /path/to/logfile.log

This will append the output of your script to the log file.

Example 9: Emailing Output

To email the output of your cron task, you can use the following command:

MAILTO=user@example.com
* * * * * /path/to/script.sh

This will email the output of your script to the specified email address.

Example 10: Running Multiple Tasks

To run multiple tasks at the same time, you can add multiple lines to your crontab file:

* * * * * /path/to/script1.sh
* * * * * /path/to/script2.sh

This will run both scripts every minute.

Conclusion

Cron is a powerful tool in Linux that can save you time and make your life easier. With these 10 examples, you can schedule tasks to run at specified intervals, redirect output to a log file or email, and run multiple tasks simultaneously. Use cron wisely and get the most out of your Linux system!

Like(0)