Job.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. class Job:
  2. # Base class for cpu-intensive or non-time-critical operations that
  3. # are run through the JobManager.
  4. # values to yield from your run() generator method
  5. Done = object()
  6. Continue = None # 'yield None' is acceptable in place of 'yield Job.Continue'
  7. Priorities = ScratchPad(Low=-100, Normal=0, High=100)
  8. _SerialGen = SerialNumGen()
  9. def __init__(self, name):
  10. self._name = name
  11. self._generator = None
  12. self._id = Job._SerialGen.next()
  13. def destroy(self):
  14. del self._name
  15. del self._generator
  16. def run(self):
  17. # override and do your processing
  18. # yield Job.Continue when possible/reasonable
  19. # try not to run longer than the JobManager's timeslice between yields
  20. # when done, yield Job.Done
  21. raise "don't call down"
  22. def getPriority(self):
  23. # override if you want a different priority
  24. # you can use numbers other than those in Job.Priorities
  25. return Job.Priorities.Normal
  26. def suspend(self):
  27. # called when JobManager is going to stop running this job for a while
  28. # most jobs don't need to override this
  29. pass
  30. def resume(self):
  31. # called when JobManager is going to start running this job again
  32. # most jobs don't need to override this
  33. pass
  34. def _getJobId(self):
  35. return self._id
  36. def _getGenerator(self):
  37. if self._generator is None:
  38. self._generator = self.run()
  39. return self._generator
  40. if __debug__: # __dev__ not yet available at this point
  41. from direct.showbase.Job import Job
  42. class TestJob(Job):
  43. def __init__(self):
  44. Job.__init__(self, 'TestJob')
  45. self._counter = 0
  46. self._accum = 0
  47. self._finished = False
  48. def run(self):
  49. while True:
  50. while self._accum < 100:
  51. self._accum += 1
  52. print 'counter = %s, accum = %s' % (self._counter, self._accum)
  53. yield None
  54. self._accum = 0
  55. self._counter += 1
  56. if self._counter >= 100:
  57. print 'Job.Done'
  58. yield Job.Done
  59. else:
  60. yield None
  61. def addTestJob():
  62. jobMgr.add(TestJob())