定时发送消息

# -*- coding=utf-8 -*-
import random
import time
from datetime import datetime
import os

from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.schedulers.blocking import BlockingScheduler
import logging

logging.basicConfig()
logging.getLogger('apscheduler').setLevel(logging.DEBUG)

scheduler = BackgroundScheduler()


def tick():
    sec = random.randint(2, 6)
    temp_dict = {"seconds": sec}
    # temp_trigger = scheduler._create_trigger(trigger='interval', trigger_args=temp_dict)
    # scheduler.modify_job("jobid", trigger=temp_trigger)
    print('Tick! The time is: %s' % datetime.now())
    print("这条信息的 下条 发送延迟{}秒执行".format(sec))
    time.sleep(sec-1)



if __name__ == '__main__':
    job = scheduler.add_job(tick, 'interval', max_instances=1, id="jobid", seconds=1)
    print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C    '))

    try:
        scheduler.start()
        print("数量:", scheduler.get_jobs())
        for i in range(5):
            time.sleep(1)
            print("main>>>>>>>>>>>>>")
        scheduler.shutdown()
        # scheduler.pause_job("jobid")
        # print("pause")
        # print("数量:", scheduler.get_jobs())
        # time.sleep(5)
        # scheduler.resume_job("jobid")
        # print("start....")
        print("数量:", scheduler.get_jobs())
        print("close")

        scheduler = BackgroundScheduler()
        scheduler.add_job(tick, 'interval', max_instances=1, id="jobid", seconds=1)
        scheduler.start()
        while True:
            pass
    except (KeyboardInterrupt, SystemExit):
        pass

你可能感兴趣的:(Python)