search
HomeBackend DevelopmentPython TutorialCron job management based on Python

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
How to solve the permissions problem encountered when viewing Python version in Linux terminal?How to solve the permissions problem encountered when viewing Python version in Linux terminal?Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How Do I Use Beautiful Soup to Parse HTML?How Do I Use Beautiful Soup to Parse HTML?Mar 10, 2025 pm 06:54 PM

This article explains how to use Beautiful Soup, a Python library, to parse HTML. It details common methods like find(), find_all(), select(), and get_text() for data extraction, handling of diverse HTML structures and errors, and alternatives (Sel

Serialization and Deserialization of Python Objects: Part 1Serialization and Deserialization of Python Objects: Part 1Mar 08, 2025 am 09:39 AM

Serialization and deserialization of Python objects are key aspects of any non-trivial program. If you save something to a Python file, you do object serialization and deserialization if you read the configuration file, or if you respond to an HTTP request. In a sense, serialization and deserialization are the most boring things in the world. Who cares about all these formats and protocols? You want to persist or stream some Python objects and retrieve them in full at a later time. This is a great way to see the world on a conceptual level. However, on a practical level, the serialization scheme, format or protocol you choose may determine the speed, security, freedom of maintenance status, and other aspects of the program

How to Perform Deep Learning with TensorFlow or PyTorch?How to Perform Deep Learning with TensorFlow or PyTorch?Mar 10, 2025 pm 06:52 PM

This article compares TensorFlow and PyTorch for deep learning. It details the steps involved: data preparation, model building, training, evaluation, and deployment. Key differences between the frameworks, particularly regarding computational grap

Mathematical Modules in Python: StatisticsMathematical Modules in Python: StatisticsMar 09, 2025 am 11:40 AM

Python's statistics module provides powerful data statistical analysis capabilities to help us quickly understand the overall characteristics of data, such as biostatistics and business analysis. Instead of looking at data points one by one, just look at statistics such as mean or variance to discover trends and features in the original data that may be ignored, and compare large datasets more easily and effectively. This tutorial will explain how to calculate the mean and measure the degree of dispersion of the dataset. Unless otherwise stated, all functions in this module support the calculation of the mean() function instead of simply summing the average. Floating point numbers can also be used. import random import statistics from fracti

Scraping Webpages in Python With Beautiful Soup: Search and DOM ModificationScraping Webpages in Python With Beautiful Soup: Search and DOM ModificationMar 08, 2025 am 10:36 AM

This tutorial builds upon the previous introduction to Beautiful Soup, focusing on DOM manipulation beyond simple tree navigation. We'll explore efficient search methods and techniques for modifying HTML structure. One common DOM search method is ex

What are some popular Python libraries and their uses?What are some popular Python libraries and their uses?Mar 21, 2025 pm 06:46 PM

The article discusses popular Python libraries like NumPy, Pandas, Matplotlib, Scikit-learn, TensorFlow, Django, Flask, and Requests, detailing their uses in scientific computing, data analysis, visualization, machine learning, web development, and H

How to Create Command-Line Interfaces (CLIs) with Python?How to Create Command-Line Interfaces (CLIs) with Python?Mar 10, 2025 pm 06:48 PM

This article guides Python developers on building command-line interfaces (CLIs). It details using libraries like typer, click, and argparse, emphasizing input/output handling, and promoting user-friendly design patterns for improved CLI usability.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool