Home  >  Article  >  Backend Development  >  Cron job management based on Python

Cron job management based on Python

WBOY
WBOYOriginal
2023-08-28 11:25:101066browse

Cron job management based on Python

In this tutorial, you will learn the importance of cron jobs and why you need them. You'll see python-crontab, a Python module that interacts with crontab. You will learn how to operate cron jobs from a Python program using the python-crontab module.

What is Cron?

During system administration, background jobs need to be run on the server to perform routine tasks. Cron is a system process used to perform background tasks on a regular basis. Cron requires a file called crontab that contains a list of tasks to be executed at a specific time. All these jobs are executed in the background at specified times.

To view the cron jobs running on your system, navigate to the terminal and enter:

crontab -l

The above command displays the job list in the crontab file. To add a new cron job to crontab, enter:

crontab -e

The above command will display the crontab file where you can schedule jobs. Suppose you have a file called hello.py like this:

print("Hello World")

Now, to schedule a cron job to execute the above script for output to another file, you need to add the following lines of code:

50 19 * * * python hello.py >> a.txt

The above line of code schedules the execution of the file and outputs the output to a file named a.txt. The number preceding the command to be executed defines when the job will be executed. The timing syntax has five parts:

  1. minute
  2. Hour
  3. Someday in January
  4. moon
  5. Day of the week

The asterisk (*) in the timing syntax means it will run every time.

Python-Crontab Introduction

python-crontab is a Python module that provides access to cron jobs and enables us to manipulate crontab files from a Python program. It automates the process of manually modifying crontab files. To start using python-crontab, you need to install the module using pip:

pip install python-crontab

After installing python-crontab, import it into the Python program.

from crontab import CronTab

Write your first Cron job

Let's use the python-crontab module to write our first cron job. Create a Python program named writeDate.py. In writeDate.py, add code to print the current date and time to a file. This is what writeDate.py looks like:

import datetime

with open('dateInfo.txt','a') as outFile:
    outFile.write('\n' + str(datetime.datetime.now()))

Save the above changes.

Let’s create another Python program that will schedule the writeDate.py Python program to run every minute. Create a file named scheduleCron.py.

Import the CronTab module into the scheduleCron.py program.

from crontab import CronTab

Using the CronTab module, we access the system crontab.

my_cron = CronTab(user='your username')

The above command creates the user's access rights to the system crontab. Let's loop through the cron jobs and you should be able to see any cron job that was manually created for a specific username.

for job in my_cron:
    print(job)

Save the changes and try executing scheduleCron.py, you should have a list of cron jobs for the specific user (if any). You should be able to see something similar when executing the above program:

50 19 * * * python hello.py >> a.txt # at 5 a.m every week with:

Let's continue by creating a new cron job using the CronTab module. You can use the new method to create a new cron and specify the command to execute.

job = my_cron.new(command='python /home/jay/writeDate.py')

As you can see in the above line of code, I have specified the command to be executed when the cron job executes. Once you have a new cron job, you need to schedule the cron job.

Let's schedule a cron job to run every minute. Therefore, at one-minute intervals, the current date and time will be appended to the dateInfo.txt file. To schedule the job to execute every minute, add the following lines of code:

job.minute.every(1)

After scheduling the job, you need to write the job to the cron tab.

my_cron.write()

This is scheduleCron.py file:

from crontab import CronTab

my_cron = CronTab(user='vaati')
job = my_cron.new(command='python3 /home/Desktop/vaati/writeDate.py')
job.minute.every(1)

my_cron.write()

Save the above changes and execute the Python program.

python scheduleCron.py

After execution, use the following command to check the crontab file:

crontab -l

The above command should show the newly added cron job.

* * * * * python3 home/vaati/Desktop/writeDate.py

Wait a moment and check your home directory, you should be able to see the dateInfo.txt file, which contains the current date and time. The file will be updated every minute and the current date and time will be appended to the existing content.

更新现有的 Cron 作业

要更新现有的 cron 作业,您需要使用命令或使用 ID 来查找 cron 作业。使用 python-crontab 创建 cron 作业时,可以以注释的形式为 cron 作业设置 Id。以下是如何创建带有注释的 cron 作业:

job = my_cron.new(command='python3 home/vaati/Desktop/writeDate.py', comment='dateinfo')

如上面的代码行所示,已使用注释 dateinfo 创建了一个新的 cron 作业。上述注释可用于查找 cron 作业。

您需要做的是迭代 crontab 中的所有作业,并使用注释 dateinfo 检查作业。这是代码:

 my_cron = CronTab(user='vaati')
 for job in my_cron:
     print(job)

使用 job.comment 属性检查每个作业的评论。

 my_cron = CronTab(user='vaati')
 for job in my_cron:
     if job.comment == 'dateinfo':
         print(job)

完成作业后,重新安排 cron 作业并写入 cron。完整代码如下:

from crontab import CronTab

my_cron = CronTab(user='vaati')
for job in my_cron:
    if job.comment == 'dateinfo':
        job.hour.every(10)
        my_cron.write()
        print('Cron job modified successfully')

保存上述更改并执行 scheduleCron.py 文件。使用以下命令列出 crontab 文件中的项目:

crontab -l

您应该能够看到带有更新的计划时间的 cron 作业。

* */10 * * * python3 /home/Desktop/vaati/writeDate.py # dateinfo

从 Crontab 清除作业

python-crontab 提供了从 crontab 中清除或删除作业的方法。您可以根据计划、注释或命令从 crontab 中删除 cron 作业。

假设您想通过 crontab 中的注释 dateinfo 清除作业。代码是:

from crontab import CronTab

my_cron = CronTab(user='vaati')
for job in my_cron
    if job.comment == 'dateinfo':
        my_cron.remove(job)
        my_cron.write()

同样,要根据评论删除作业,可以直接调用 my_cron 上的 remove 方法,无需任何迭代。这是代码:

my_cron.remove(comment='dateinfo')

要删除 crontab 中的所有作业,可以调用 remove_all 方法。

my_cron.remove_all()

完成更改后,使用以下命令将其写回 cron:

my_cron.write()

计算工作频率

要检查使用 python-crontab 执行作业的次数,您可以使用 Frequency 方法。获得作业后,您可以调用名为 Frequency 的方法,该方法将返回该作业在一年内执行的次数。

from crontab import CronTab

my_cron = CronTab(user='vaati')
for job in my_cron:
    print(job.frequency())

要查看一小时内作业执行的次数,可以使用方法 Frequency_per_hour

my_cron = CronTab(user='vaati')
for job in my_cron:
    print(job.frequency_per_hour())

要查看一天中的作业频率,可以使用方法 Frequency_per_day

检查作业计划

python-crontab 提供了检查特定作业的时间表的功能。为此,您需要在系统上安装 croniter 模块。使用 pip 安装 croniter

pip install croniter

安装 croniter 后,调用作业上的调度方法来获取作业调度。

import datetime

sch = job.schedule(date_from=datetime.datetime.now())

现在您可以使用 get_next 方法获取下一个作业计划。

print(sch.get_next())

完整代码如下:

import datetime
from crontab import CronTab

my_crons = CronTab(user='vaati')
for job in my_crons:
    sch = job.schedule(date_from=datetime.datetime.now())
    print(sch.get_next())

您甚至可以使用 get_prev 方法获取之前的时间表。

总结

在本教程中,您了解了如何开始使用 python-crontab 从 Python 程序访问系统 crontab。使用 python-crontab,您可以自动执行创建、更新和调度 cron 作业的手动过程。

您是否使用过 python-crontab 或任何其他库来访问系统 crontab ?我很想听听你的想法。请在论坛上告诉我们您的建议。

学习Python

无论您是刚刚入门还是希望学习新技能的经验丰富的程序员,都可以通过我们完整的 Python 教程指南学习 Python。

The above is the detailed content of Cron job management based on Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn