python里实现并行 多线程后台运行程序的方法

方法一:
使用装饰器

from apscheduler.scheduler import Scheduler
sched = Scheduler()  # 实例化,固定格式
def test1():
    print(1)
@sched.interval_schedule(seconds=30)  # 装饰器,seconds=60意思为该函数为1分钟运行一次
def mytask():
    test1()
sched.start()  # 启动该脚本

方法二:使用 thread

import threading
import time

def one():
	while 1: 
		print(1)
        time.sleep(5)

def two():
	while 1 :
    	print('a')
    	time.sleep(6)

threads = []
t1 = threading.Thread(target=one)
threads.append(t1)
t2 = threading.Thread(target=two)
threads.append(t2)
if __name__=='__main__':
    for t in threads:
        t.start()
    for t in threads:
        t.join()
print ("out")

发布了69 篇原创文章 · 获赞 14 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_41147129/article/details/89330281
今日推荐