Python 在X秒内调用函数
在函数中,我希望每2秒钟调用一行。每当我使用sleep函数时,代码都会等待2秒钟,然后转到下一条指令。但是,我希望在不干扰其他指令的情况下,每2秒钟调用一个函数。榜样Python 在X秒内调用函数,python,Python,在函数中,我希望每2秒钟调用一行。每当我使用sleep函数时,代码都会等待2秒钟,然后转到下一条指令。但是,我希望在不干扰其他指令的情况下,每2秒钟调用一个函数。榜样 a = None def foo(): bar() a = a * 12 print "A : ",a def bar(): a = 0 每两秒钟,应重置一次。但是,在两秒钟内,a的值应递增并显示。可能吗?怎么做?你可以在这个时候投票。也就是说,读取当前时间,存储它,处理你的东西,然后忙碌地
a = None
def foo():
bar()
a = a * 12
print "A : ",a
def bar():
a = 0
每两秒钟,应重置一次。但是,在两秒钟内,a的值应递增并显示。可能吗?怎么做?你可以在这个时候投票。也就是说,读取当前时间,存储它,处理你的东西,然后忙碌地等待,直到当前时间与存储的时间匹配+2秒。如果你想,你可以在你的东西之后再加上睡眠。但要确保在2秒间隔结束之前完成睡眠。例如,只睡1.5秒 如果您想独立运行它,则需要使用线程。 你也可以考虑一下这里的答案:
你可以暂时投票。也就是说,读取当前时间,存储它,处理你的东西,然后忙碌地等待,直到当前时间与存储的时间匹配+2秒。如果你想,你可以在你的东西之后再加上睡眠。但要确保在2秒间隔结束之前完成睡眠。例如,只睡1.5秒 如果您想独立运行它,则需要使用线程。 你也可以考虑一下这里的答案:
使用。但仅仅在单独的计时器中运行代码中的bar是不起作用的,您必须首先考虑在线程之间使用变量。使用。但仅仅在单独的计时器中运行代码中的bar是不起作用的,您必须首先考虑在线程之间使用变量。我将使用线程和锁来满足您的需要 事实上,我喜欢我的一个朋友Pepe编写的开源线程池 以下是线程池代码,然后是一个可能的解决方案:
#! /usr/bin/python
# -*- coding: utf-8 -*-
# File: threadPool.py
import threading
import Queue
import time
import sys
import traceback
import datetime
Instance = None
def getInstance():
global Instance
if not Instance:
Instance = ThreadPool()
return Instance
class ThreadPool:
def __init__(self,maxWorkers = 10):
self.tasks = Queue.Queue()
self.workers = 0
self.working = 0
self.maxWorkers = maxWorkers
self.allKilled = threading.Event()
self.countLock = threading.RLock()
self.timers = {}
self.timersLock = threading.Lock()
self.timersThreadLock = threading.Lock()
self.timersEvent = threading.Event()
self.allKilled.set()
def run(self,target,callback = None, *args, **kargs):
""" starts task.
target = callable to run with *args and **kargs arguments.
callback = callable executed when target ends
callback sould accept one parameter where target's
return value is passed.
If callback is None it's ignored.
"""
self.countLock.acquire()
if not self.workers:
self.addWorker()
self.countLock.release()
self.tasks.put((target,callback,args,kargs))
def setMaxWorkers(self,num):
""" Sets the maximum workers to create.
num = max workers
If number passed is lower than active workers
it will kill workers to match that number.
"""
self.countLock.acquire()
self.maxWorkers = num
if self.workers > self.maxWorkers:
self.killWorker(self.workers - self.maxWorkers)
self.countLock.release()
def addWorker(self,num = 1):
""" Add workers.
num = number of workers to create/add.
"""
for x in xrange(num):
self.countLock.acquire()
self.workers += 1
self.allKilled.clear()
self.countLock.release()
t = threading.Thread(target = self.__workerThread)
t.setDaemon(True)
t.start()
def killWorker(self,num = 1):
""" Kill workers.
num = number of workers to kill.
"""
self.countLock.acquire()
if num > self.workers:
num = self.workers
self.countLock.release()
for x in xrange(num):
self.tasks.put("exit")
def killAllWorkers(self,wait = None):
""" Kill all active workers.
wait = seconds to wait until last worker ends
if None it waits forever.
"""
self.countLock.acquire()
self.killWorker(self.workers)
self.countLock.release()
self.allKilled.wait(wait)
def __workerThread(self):
while True:
task = self.tasks.get()
# exit is "special" tasks to kill thread
if task == "exit":
break
self.countLock.acquire()
self.working += 1
if (self.working >= self.workers) and (self.workers < self.maxWorkers): # create thread on demand
self.addWorker()
self.countLock.release()
fun,cb,args,kargs = task
try:
ret = fun(*args,**kargs)
if cb:
cb(ret)
except:
ty,val,tb = sys.exc_info()
print "Thread Catch:%s" % "".join(traceback.format_exception(ty,val,tb))
self.countLock.acquire()
self.working -= 1
self.countLock.release()
del(fun) # Dereference all
del(cb)
del(args)
del(kargs)
del(task)
self.countLock.acquire()
self.workers -= 1
if not self.workers:
self.allKilled.set()
self.countLock.release()
def timer(self, cb, period):
""" Add or remove timers.
cb = callback function.
period = period in seconds (float)
if period is 0 timer is deleted.
"""
self.run(self.__timerThread, None, cb, period)
def __timerThread(self, cb, period):
self.timersLock.acquire()
self.timersEvent.set()
if not period:
if cb in self.timers:
del(self.timers[cb])
self.timersLock.release()
return
self.timers[cb] = [period,time.time()]
self.timersLock.release()
if not self.timersThreadLock.acquire(0):
return
while True:
self.timersLock.acquire()
if len(self.timers) == 0:
self.timersThreadLock.release()
self.timersLock.release()
break
minWait = 30*24*3600
now = time.time()
for k,v in self.timers.items():
period, last = v
wait = period - (now - last)
if wait <=0:
self.run(k)
wait = period
v[1] = now
if wait < minWait:
minWait = wait
self.timersLock.release()
self.timersEvent.wait(minWait)
self.timersEvent.clear()
#! /usr/bin/python
# -*- coding: utf-8 -*-
# File: a.py
import threadPool
import time
import threading
class A:
def __init__(self):
self.a = 1
self.alock = threading.Lock()
self.tp = threadPool.getInstance()
def bar(self):
self.alock.acquire()
self.a = 1
self.alock.release()
def foo(self):
self.tp.timer(self.bar, 2)
while True:
self.alock.acquire()
self.a = self.a * 12
self.alock.release()
print "A : ",self.a
time.sleep(0.1)
a = A()
a.foo()
运行:
我会使用线程和锁来满足您的需求 事实上,我喜欢我的一个朋友Pepe编写的开源线程池 以下是线程池代码,然后是一个可能的解决方案:
#! /usr/bin/python
# -*- coding: utf-8 -*-
# File: threadPool.py
import threading
import Queue
import time
import sys
import traceback
import datetime
Instance = None
def getInstance():
global Instance
if not Instance:
Instance = ThreadPool()
return Instance
class ThreadPool:
def __init__(self,maxWorkers = 10):
self.tasks = Queue.Queue()
self.workers = 0
self.working = 0
self.maxWorkers = maxWorkers
self.allKilled = threading.Event()
self.countLock = threading.RLock()
self.timers = {}
self.timersLock = threading.Lock()
self.timersThreadLock = threading.Lock()
self.timersEvent = threading.Event()
self.allKilled.set()
def run(self,target,callback = None, *args, **kargs):
""" starts task.
target = callable to run with *args and **kargs arguments.
callback = callable executed when target ends
callback sould accept one parameter where target's
return value is passed.
If callback is None it's ignored.
"""
self.countLock.acquire()
if not self.workers:
self.addWorker()
self.countLock.release()
self.tasks.put((target,callback,args,kargs))
def setMaxWorkers(self,num):
""" Sets the maximum workers to create.
num = max workers
If number passed is lower than active workers
it will kill workers to match that number.
"""
self.countLock.acquire()
self.maxWorkers = num
if self.workers > self.maxWorkers:
self.killWorker(self.workers - self.maxWorkers)
self.countLock.release()
def addWorker(self,num = 1):
""" Add workers.
num = number of workers to create/add.
"""
for x in xrange(num):
self.countLock.acquire()
self.workers += 1
self.allKilled.clear()
self.countLock.release()
t = threading.Thread(target = self.__workerThread)
t.setDaemon(True)
t.start()
def killWorker(self,num = 1):
""" Kill workers.
num = number of workers to kill.
"""
self.countLock.acquire()
if num > self.workers:
num = self.workers
self.countLock.release()
for x in xrange(num):
self.tasks.put("exit")
def killAllWorkers(self,wait = None):
""" Kill all active workers.
wait = seconds to wait until last worker ends
if None it waits forever.
"""
self.countLock.acquire()
self.killWorker(self.workers)
self.countLock.release()
self.allKilled.wait(wait)
def __workerThread(self):
while True:
task = self.tasks.get()
# exit is "special" tasks to kill thread
if task == "exit":
break
self.countLock.acquire()
self.working += 1
if (self.working >= self.workers) and (self.workers < self.maxWorkers): # create thread on demand
self.addWorker()
self.countLock.release()
fun,cb,args,kargs = task
try:
ret = fun(*args,**kargs)
if cb:
cb(ret)
except:
ty,val,tb = sys.exc_info()
print "Thread Catch:%s" % "".join(traceback.format_exception(ty,val,tb))
self.countLock.acquire()
self.working -= 1
self.countLock.release()
del(fun) # Dereference all
del(cb)
del(args)
del(kargs)
del(task)
self.countLock.acquire()
self.workers -= 1
if not self.workers:
self.allKilled.set()
self.countLock.release()
def timer(self, cb, period):
""" Add or remove timers.
cb = callback function.
period = period in seconds (float)
if period is 0 timer is deleted.
"""
self.run(self.__timerThread, None, cb, period)
def __timerThread(self, cb, period):
self.timersLock.acquire()
self.timersEvent.set()
if not period:
if cb in self.timers:
del(self.timers[cb])
self.timersLock.release()
return
self.timers[cb] = [period,time.time()]
self.timersLock.release()
if not self.timersThreadLock.acquire(0):
return
while True:
self.timersLock.acquire()
if len(self.timers) == 0:
self.timersThreadLock.release()
self.timersLock.release()
break
minWait = 30*24*3600
now = time.time()
for k,v in self.timers.items():
period, last = v
wait = period - (now - last)
if wait <=0:
self.run(k)
wait = period
v[1] = now
if wait < minWait:
minWait = wait
self.timersLock.release()
self.timersEvent.wait(minWait)
self.timersEvent.clear()
#! /usr/bin/python
# -*- coding: utf-8 -*-
# File: a.py
import threadPool
import time
import threading
class A:
def __init__(self):
self.a = 1
self.alock = threading.Lock()
self.tp = threadPool.getInstance()
def bar(self):
self.alock.acquire()
self.a = 1
self.alock.release()
def foo(self):
self.tp.timer(self.bar, 2)
while True:
self.alock.acquire()
self.a = self.a * 12
self.alock.release()
print "A : ",self.a
time.sleep(0.1)
a = A()
a.foo()
运行:
你需要学习(并且学到很多)关于线程的知识。请注意,
a
不是在foo
和bar
之间共享的。在您的示例中,它们是独立的局部变量。@MartijnPieters对不起,我忘了。答案简单吗?在线程之间共享变量可能很复杂。它要求您了解线程和线程安全。@MartijnPieters在foo函数中,是否有任何键(如schedule)放在bar之后,以便像foo bar()中那样对其进行调度。schedule(2)?您需要学习(并学到很多)关于线程的知识。请注意,a
不是在foo
和bar
之间共享的。在您的示例中,它们是独立的局部变量。@MartijnPieters对不起,我忘了。答案简单吗?在线程之间共享变量可能很复杂。它要求您了解线程和线程安全。@MartijnPieters在foo函数中,是否有任何键(如schedule)放在bar之后,以便它可以被调度,如foo bar()中的。schedule(2)?