[Linux] Use Cron to automatically check and execute tasks

Using Cron jobs is a very useful method when you need to check and execute tasks regularly. In this article, we will learn how to set up a Cron job to check for the presence of screen every minute/hour and perform corresponding actions if needed.

Step 1: Open Terminal and edit Cron task list

First, open a terminal and run the following command to edit the Cron task list:

crontab -e

Step 2: Add Cron Job

In the Cron task list, add the following line, this will make the system check if screen exists every minute

* * * * * /path/to/check_screen.sh

If you add the following line, this will perform the action on the first minute of every hour (on the hour).

1 * * * * /path/to/check_screen.sh

These two lines specify the execution frequency of the Cron job. The * * * * * in the first line means it will run every minute, while the 1 * * * * in the second line means it will run once every hour on the first minute (the hour).

Step 3: Create check_screen.sh script

Next, create a Bash script called check_screen.sh and add the following content to the file:

#!/bin/bash

# 检查是否存在指定的screen会话
if ! screen -list | grep "your_screen_name"; then
    # 如果screen不存在,则创建它并执行python main.py
    screen -S your_screen_name -d -m python /path/to/main.py
fi

The purpose of this script is to check if a screen session named your_screen_name exists. If the session does not exist, create it and execute the Python program in /path/to/main.py. Make sure to replace your_screen_name and /path/to/main.py with your actual session name and Python program path.

Step 4: Add execution permissions to the script

Run the following command to add execution permissions to the check_screen.sh script:

chmod +x /path/to/check_screen.sh

in conclusion

Now you have set up a Cron job that will check if screen exists every minute\hour and take action if needed. This is a powerful tool that can be used to automate repetitive tasks and ensure they are performed as planned. Depending on your needs, you can adjust the execution frequency of jobs based on Cron's syntax.

Guess you like

Origin blog.csdn.net/linjiuxiansheng/article/details/133658350