Table of Contents
What is Cron?
Python-Crontab Introduction
Write your first Cron job
更新现有的 Cron 作业
从 Crontab 清除作业
计算工作频率
检查作业计划
总结
学习Python
Home Backend Development Python Tutorial Cron job management based on Python

Cron job management based on Python

Aug 28, 2023 am 11:25 AM

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
Copy after login
Copy after login
Copy after login

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

crontab -e
Copy after login

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")
Copy after login

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
Copy after login

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
Copy after login

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

from crontab import CronTab
Copy after login
Copy after login

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()))
Copy after login

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
Copy after login
Copy after login

Using the CronTab module, we access the system crontab.

my_cron = CronTab(user='your username')
Copy after login

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)
Copy after login

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:
Copy after login

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')
Copy after login

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)
Copy after login

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

my_cron.write()
Copy after login
Copy after login

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()
Copy after login

Save the above changes and execute the Python program.

python scheduleCron.py
Copy after login

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

crontab -l
Copy after login
Copy after login
Copy after login

The above command should show the newly added cron job.

* * * * * python3 home/vaati/Desktop/writeDate.py
Copy after login

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')
Copy after login

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

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

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

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

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

完成作业后,重新安排 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')
Copy after login

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

crontab -l
Copy after login
Copy after login
Copy after login

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

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

从 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()
Copy after login

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

my_cron.remove(comment='dateinfo')
Copy after login

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

my_cron.remove_all()
Copy after login

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

my_cron.write()
Copy after login
Copy after login

计算工作频率

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

from crontab import CronTab

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

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

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

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

检查作业计划

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

pip install croniter
Copy after login

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

import datetime

sch = job.schedule(date_from=datetime.datetime.now())
Copy after login

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

print(sch.get_next())
Copy after login

完整代码如下:

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())
Copy after login

您甚至可以使用 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 of this Website
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

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)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to Use Python to Find the Zipf Distribution of a Text File How to Use Python to Find the Zipf Distribution of a Text File Mar 05, 2025 am 09:58 AM

This tutorial demonstrates how to use Python to process the statistical concept of Zipf's law and demonstrates the efficiency of Python's reading and sorting large text files when processing the law. You may be wondering what the term Zipf distribution means. To understand this term, we first need to define Zipf's law. Don't worry, I'll try to simplify the instructions. Zipf's Law Zipf's law simply means: in a large natural language corpus, the most frequently occurring words appear about twice as frequently as the second frequent words, three times as the third frequent words, four times as the fourth frequent words, and so on. Let's look at an example. If you look at the Brown corpus in American English, you will notice that the most frequent word is "th

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

How to Download Files in Python How to Download Files in Python Mar 01, 2025 am 10:03 AM

Python provides a variety of ways to download files from the Internet, which can be downloaded over HTTP using the urllib package or the requests library. This tutorial will explain how to use these libraries to download files from URLs from Python. requests library requests is one of the most popular libraries in Python. It allows sending HTTP/1.1 requests without manually adding query strings to URLs or form encoding of POST data. The requests library can perform many functions, including: Add form data Add multi-part file Access Python response data Make a request head

Image Filtering in Python Image Filtering in Python Mar 03, 2025 am 09:44 AM

Dealing with noisy images is a common problem, especially with mobile phone or low-resolution camera photos. This tutorial explores image filtering techniques in Python using OpenCV to tackle this issue. Image Filtering: A Powerful Tool Image filter

How to Work With PDF Documents Using Python How to Work With PDF Documents Using Python Mar 02, 2025 am 09:54 AM

PDF files are popular for their cross-platform compatibility, with content and layout consistent across operating systems, reading devices and software. However, unlike Python processing plain text files, PDF files are binary files with more complex structures and contain elements such as fonts, colors, and images. Fortunately, it is not difficult to process PDF files with Python's external modules. This article will use the PyPDF2 module to demonstrate how to open a PDF file, print a page, and extract text. For the creation and editing of PDF files, please refer to another tutorial from me. Preparation The core lies in using external module PyPDF2. First, install it using pip: pip is P

How to Cache Using Redis in Django Applications How to Cache Using Redis in Django Applications Mar 02, 2025 am 10:10 AM

This tutorial demonstrates how to leverage Redis caching to boost the performance of Python applications, specifically within a Django framework. We'll cover Redis installation, Django configuration, and performance comparisons to highlight the bene

Introducing the Natural Language Toolkit (NLTK) Introducing the Natural Language Toolkit (NLTK) Mar 01, 2025 am 10:05 AM

Natural language processing (NLP) is the automatic or semi-automatic processing of human language. NLP is closely related to linguistics and has links to research in cognitive science, psychology, physiology, and mathematics. In the computer science

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

See all articles