我有一个线程每小时检查一次并不断更新全局变量,由于某种原因全局语句不起作用,即使线程更新它,它也会在全局变量中保持相同的值,请参考我的代码:
paymentDate = "2024-03-22"
currentDate = ""
#Function that is in charge of validate the date
def isSystemValidDateReached():
global currentDate
try:
if currentDate == "":
currentDate = str(urlopen('http://just-the-time.appspot.com').read().strip().decode('utf-8'))
if paymentDate < currentDate:
return True
else:
return False
except Exception as e:
log.appendToLog("Error", "critical")
#function that is being used in a thread
def getTimeFromInternet(timeSleep=3600):
global currentDate
while True:
try:
time.sleep(timeSleep)
currentDate = str(urlopen('http://just-the-time.appspot.com').read().strip().decode('utf-8'))
print("new current date {}".format(currentDate))
except Exception as e:
log.appendToLog("Error: {}".format(e), "critical")
这是主脚本中的一部分,并且每隔一定时间都会在 while 循环中检查此函数:
if isSystemValidDateReached():
exit()
# get time every hour
getDateFunctionThread = multiprocessing.Process(target=getTimeFromInternet)
getDateFunctionThread.start()
我面临的问题是我在
getTimeFromInternet
函数中有一个断点,并且它更新了 currentDate
,但是当调用函数 isSystemValidDateReached()
时,我看到在这部分代码中分配了相同的旧值:
if currentDate == "":
currentDate = str(urlopen('http://just-the-time.appspot.com').read().strip().decode('utf-8'))
需要更改什么才能让该变量在我的线程函数中每小时更新一次?
正如chepner所说,如何解决是因为我使用的是多处理而不是线程,请参阅代码如下:
getDateFunctionThread = Thread(target=getTimeFromInternet)
getDateFunctionThread.start()