2009
08.18

Timer threads

Timers have all sorts of uses, and unfortunately up until 8.5 Maya had no good way of checking a timer, and running a background event.

Previously you could check system time at certain events with a scriptJob, like selectionChanged, but it tends to slow Maya down right when the user was trying to interact.. so in a production environment that wasn’t a viable solution (usually scriptJobs aren’t, as nifty as they are).

Now, with the flexibility of python in Maya, and python’s ability to create threads, it’s quite simple to create a basic Timer class.

Note: I updated it to use threading.Event().wait() instead of a time.sleep() loop, and now I directly subclass threading.Thread.

'''
Usage:
def timerTest():
	print 'Hello World!'

#create and start a timer
timer = Timer(30, timerTest, repeat=True)
timer.start()

#To stop the timer
timer.stop()
'''

import threading

try:
	from maya.utils import executeInMainThreadWithResult
except:
	executeInMainThreadWithResult = None

class Timer(threading.Thread):
	def __init__(self, interval, function, args=[], kwargs={}, repeat=True):
		self.interval = interval
		self.function = function
		self.repeat = repeat
		self.args = args
		self.kwargs = kwargs
		self.event = threading.Event()
		threading.Thread.__init__(self)

	def run(self):
		def _mainLoop():
			self.event.wait(self.interval)
			if not self.event.isSet():
				if executeInMainThreadWithResult:
					executeInMainThreadWithResult(self.function, *self.args, **self.kwargs)
				else:
					self.function(*self.args, **self.kwargs)

		if self.repeat:
			while not self.event.isSet():
				_mainLoop()
		else:
			_mainLoop()
			self.stop()

	def start(self):
		self.event.clear()
		threading.Thread.start(self)

	def stop(self):
		self.event.set()
		threading.Thread.__init__(self)
”’
Usage:
def timerTest():
print ‘Hello World!’
#create and start a timer
timer = Timer(30, timerTest, repeat=True)
timer.start()
#To stop the timer
timer.stop()
”’
import threading
try:
from maya.utils import executeInMainThreadWithResult
except:
executeInMainThreadWithResult = None
class Timer(threading.Thread):
def __init__(self, interval, function, args=[], kwargs={}, repeat=True):
self.interval = interval
self.function = function
self.repeat = repeat
self.args = args
self.kwargs = kwargs
self.event = threading.Event()
threading.Thread.__init__(self)
def run(self):
def _mainLoop():
self.event.wait(self.interval)
if not self.event.isSet():
if executeInMainThreadWithResult:
executeInMainThreadWithResult(self.function, *self.args, **self.kwargs)
else:
self.function(*self.args, **self.kwargs)
if self.repeat:
while not self.event.isSet():
_mainLoop()
else:
_mainLoop()
self.stop()
def start(self):
self.event.clear()
threading.Thread.start(self)
def stop(self):
self.event.set()
threading.Thread.__init__(self)
  1. great stuff nathan !!!

You must be logged in to post a comment.