Bootstrap

python 多线程 以及 定时任务

安装包
pip install APScheduler

# -*- coding:utf-8 -*-

from threading import Thread
from datetime import datetime, date
from apscheduler.schedulers.blocking import BlockingScheduler
import time


def recover(lis):
    for i in lis:
        print(i)
        time.sleep(0.5)

lis = [i for i in range(100)]



def main():
    threads = []
    ## 开4 个线程共同运行
    print("Start")
    for i in range(4):
        threads.append(Thread(target=recover, args=(lis[i * 25:i * 25 + 25], )))
        """
        !!! 注意 args 后面一定要加上逗号","
        """ 

    ## 启动这四个线程
    for thread in threads:
        thread.start()

    ## 等待所有线程完成
    for thread in threads:
        thread.join()
    ## 最后打印完成
    print("Done")




if __name__ == '__main__':
    scheduler = BlockingScheduler()
    ## 按间隔执行

    """
    trigger:可选 `date`, `interval` or `cron`)
    interval:
        weeks (int) – 间隔几周 
        days (int) – 间隔几天 
        hours (int) – 间隔几小时 
        minutes (int) – 间隔几分钟 
        seconds (int) – 间隔多少秒 
        start_date (datetime|str) – 开始日期 
        end_date (datetime|str) – 结束日期 
        timezone (datetime.tzinfo|str) – 时区 
    cron:
        year (int|str) – 年,4位数字 
        month (int|str) – 月 (范围1-12) 
        day (int|str) – 日 (范围1-31) 
        week (int|str) – 周 (范围1-53) 
        day_of_week (int|str) – 周内第几天或者星期几 (范围0-6 或者 mon,tue,wed,thu,fri,sat,sun) 
        hour (int|str) – 时 (范围0-23) 
        minute (int|str) – 分 (范围0-59) 
        second (int|str) – 秒 (范围0-59) 
        start_date (datetime|str) – 最早开始日期(包含) 
        end_date (datetime|str) – 最晚结束时间(包含) 
        timezone (datetime.tzinfo|str) – 指定时区 
    """
    ## 按给定时间执行
    # scheduler.add_job(timedTask, 'date', run_date="2019-10-17 13:36:00")
    # scheduler.add_job(main, 'date', run_date=datetime(2019, 10, 17, 15, 6, 0))
    # scheduler.add_job(timedTask, 'date', run_date=date(2019, 10, 17))
    ## 按时间间隔执行
    # scheduler.add_job(timedTask, 'interval', seconds=3)
    ## cron 触发器
    scheduler.add_job(main, 'cron', month='2,3,10-12', minute="*/5")

    scheduler.start()


参考文档

下面为自己写的一个类,方便调用

from threading import Thread
import threading
import math


def mul_thread(n, target, args, max_th=None):
    """
    :param n: 线程数
    :param target: 目标函数
    :param args: 参数列表
    :param max_th: 同时最多运行线程数
    :return: None
    """
    per_th = math.ceil(len(args) / n)
    threads = []
    if max_th:
        sema = threading.Semaphore(value=max_th)

        def par(arg):
            with sema:
                target(arg)

        for i in range(n):
            t = Thread(target=par, args=(args[per_th * i:per_th * (i + 1)],))
            threads.append(t)
            t.start()
    else:
        for i in range(n):
            t = Thread(target=target, args=(args[per_th * i:per_th * (i + 1)],))
            threads.append(t)
            t.start()

    for thread in threads:
        thread.join()


if __name__ == '__main__':
    import time


    def aa(m):
        time.sleep(2)
        print(sum(m))


    ll = [i for i in range(20)]
    mul_thread(5, aa, ll, 3)
    print("DOne")