在 python 中定期和异步检索值
Retrieving the values periodically and asynchronously in python
我有以下 python 脚本。我想每隔 10 秒重复执行一次 timer
函数,我是 运行 异步的。我查看了 post1 and post2,但它们没有返回任何值。
import threading
def timer(bar, baz):
print 'hello {0}'.format(bar)
return 'foo' + baz
from multiprocessing.pool import ThreadPool
pool = ThreadPool(processes=1)
async_result = pool.apply_async(timer, ('world', 'foo'))
return_val = async_result.get()
print return_val
有没有办法在主线程还在做其他工作的同时,每隔 t 个时间间隔获取值?
使用链接到的内容的一种方法:
from threading import Timer
from multiprocessing.pool import ThreadPool
from time import sleep
def getLast():
global got
Timer(10,getLast).start()
got = async_result.get()
def action(bar, baz):
print 'hello {0}'.format(bar)
return 'foo ' + baz
pool = ThreadPool(processes=1)
async_result = pool.apply_async(action, ('world', 'foo'))
Timer(10,getLast).start()
string = 'a'
while True:
got = None
while got is None:
sleep(2)
print 'Doing stuff'
print 'Got:',got
async_result = pool.apply_async(action, ('world', 'foo '+string))
string +='a'
got = None
内部 while 模拟主线程 'doing stuff',每 10 秒你应该从 async_result 获得一个新结果,并跳转启动一个新的非阻塞 运行。外循环只保留主线程运行ning.
我有以下 python 脚本。我想每隔 10 秒重复执行一次 timer
函数,我是 运行 异步的。我查看了 post1 and post2,但它们没有返回任何值。
import threading
def timer(bar, baz):
print 'hello {0}'.format(bar)
return 'foo' + baz
from multiprocessing.pool import ThreadPool
pool = ThreadPool(processes=1)
async_result = pool.apply_async(timer, ('world', 'foo'))
return_val = async_result.get()
print return_val
有没有办法在主线程还在做其他工作的同时,每隔 t 个时间间隔获取值?
使用链接到的内容的一种方法:
from threading import Timer
from multiprocessing.pool import ThreadPool
from time import sleep
def getLast():
global got
Timer(10,getLast).start()
got = async_result.get()
def action(bar, baz):
print 'hello {0}'.format(bar)
return 'foo ' + baz
pool = ThreadPool(processes=1)
async_result = pool.apply_async(action, ('world', 'foo'))
Timer(10,getLast).start()
string = 'a'
while True:
got = None
while got is None:
sleep(2)
print 'Doing stuff'
print 'Got:',got
async_result = pool.apply_async(action, ('world', 'foo '+string))
string +='a'
got = None
内部 while 模拟主线程 'doing stuff',每 10 秒你应该从 async_result 获得一个新结果,并跳转启动一个新的非阻塞 运行。外循环只保留主线程运行ning.