线程进程是操作系统的概念,当年学过,也没想到真有一天会用到操作系统这门课程的知识,先说一下项目驱动的生产环境下的场景。楼主在做项目过程中,需要调用第三方接口,然而第三方接口有access_token,acess_token 是一个月就会失效的,然而生产环境下,你不可能,一个月,重新发布一版本,而且版本只做一个access_token的更新,面对这个问题楼主有解决方案,如下
1.每次调用第三方接口的时候,都调用一次获取access_token的方法。这样就不用担心access_token会挂。
2.写一个try,catch,如果调用失败执行acess_token的生成方法更新acess_token
3.写一个线程去守护这个主进程,线程里面每隔半个月,且在半个月的凌晨去更新这个acess_token,最终实现一个主线程提供web服务,并处理http请求的相关内容,一个线程更新access_token。
楼主在这里采用了第三种方案,就是开辟一个线程,
def createThread(name,target,args=(),autoRun=True,daemon=True): def threadProc(): log.i("thread %s started!",name) try: target(*args) log.i("thread %s ended!",name) except Exception as e: log.e("thread %s crash!err=%s",name,e) thd=threading.Thread(name=name,target=threadProc) thd.setDaemon(daemon) if autoRun:thd.start() return thd首先在主进程中,main里面写上一个线程
assistant.createThread(name="token_thread", target=token_thread)守护主进程,在最外层开辟一块空间,定义一个access_token=‘111123afawf'
在子函数对全局变量进行修改的话,要使用global定义这个变量声明一下,要不然即使修改了全局变量生命周期也只有当前这个函数,在其他函数内就是和原先值是一样的。
def token_thread(): while True: now_time = datetime.datetime.now() # 获取明天时间 next_time = now_time + datetime.timedelta(days=+29) next_year = next_time.date().year next_month = next_time.date().month next_day = next_time.date().day # 获取29天后的3点时间 next_time = datetime.datetime.strptime(str(next_year) + "-" + str(next_month) + "-" + str(next_day) + " 03:00:00", "%Y-%m-%d %H:%M:%S") timer_start_time = (next_time - now_time).total_seconds() host = 'htxxxxxxxg' request = urllib.request.Request(host) request.add_header('Content-Type', 'application/json; charset=UTF-8') response = urllib.request.urlopen(request) content = response.read() keyDict = eval(content) global access_token ### 要加global 才是对全局变量的修改 access_token = keyDict['access_token'] log.i("access_token has been refreshed") log.i("access_token:%s",access_token) time.sleep(timer_start_time) print('token_thread is on')1、如果主线程是永远都不会结束的,那设置一个线程为守护线程是没必要的,设不设置都一样。
2、什么时候需要设置为守护线程?如果希望子线程一直运行,可以把子线程的代码写在while True里面一直循环,但同时要设置为守护线程,不然主线程结束了,子线程还一直运行,程序结束不了。
