用python实现crontab

本文介绍如何使用Python的schedule模块轻松实现类似crontab的定时任务功能,避免重复造轮子。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

可用schedule 模块,不必造轮子

import time
import datetime
import threading
import types

#  可用 schedule 定时任务模块

# max_thread_limit 同时执行任务数量限制


class Crontab:

    def __init__(self, job,max_thread_limit=20):
        self.job = job
        self.logfile = 'Crontab_log.txt'
        self.thread_list = []
        self.max_thread_limit = max_thread_limit

    def check(self):
        def exit_display():
            exit("joblist like [ {'name':str,'crontab':str,'func':FunctionType,'args':tuple}, ... ]")

        k = ['name', 'func', 'args', 'crontab']
        for one in self.job:
            for i in k:
                if i not in one.keys():
                    exit_display()
            if type(one['name']) is not str:
                exit_display()
            if type(one['crontab']) is not str:
                exit_display()
            if not isinstance(one['func'], types.FunctionType):
                exit_display()
            if type(one['args']) is not tuple:
                exit_display()
        return 0

    def min_clock(self, s):
        try:
            if type(s) is not str:
                print("params type is str...03 10 59")
            while True:
                tim = datetime.datetime.now().strftime('%H:%M:%S').split(":")
                if tim[2] == s:
                    time.sleep(1)
                    return 0
                else:
                    time.sleep(0.5)
                pass
        except Exception as e:
            print("min_clocl_erro\n", e)
            return -1

    @staticm
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值