Python中无休止的应用程序

Python中无休止的应用程序,python,multithreading,Python,Multithreading,我有一个python脚本,我希望总是在后台运行。该应用程序所做的是,它转到Oracle数据库并检查是否有要向用户显示的消息,如果有,则使用pynotify显示通知 我尝试使用Timer对象,但它只在选择的时间之后调用该方法。我希望它在选择时间之后每次都调用 if __name__ == '__main__': applicationName = "WEWE" # Initialization of the Notification library if not pynotify.

我有一个python脚本,我希望总是在后台运行。该应用程序所做的是,它转到Oracle数据库并检查是否有要向用户显示的消息,如果有,则使用pynotify显示通知

我尝试使用Timer对象,但它只在选择的时间之后调用该方法。我希望它在选择时间之后每次都调用

if __name__ == '__main__':
  applicationName = "WEWE"
    # Initialization of the Notification library
  if not pynotify.init(applicationName):
   sys.exit(1)         

  t = threading.Timer(5.0, runWorks)
  t.start() 
这样做行吗?还有更好的方法吗

 if __name__ == '__main__':
      applicationName = "WEEWRS"
        # Initialization of the Notification library
      if not pynotify.init(applicationName):
       sys.exit(1)         
      while True:
       t = threading.Timer(5.0, runWorks)
       t.start() 
但这给了我另一个问题

thread.error: can't start new thread

(r.py:12227): GLib-ERROR **: creating thread 'gdbus': Error creating thread: Resource temporarily unavailable

我解决了减少字符串创建的问题。下面的错误-

thread.error: can't start new thread

(r.py:12227): GLib-ERROR **: creating thread 'gdbus': Error creating thread: Resource temporarily unavailable
当缺乏资源时就会出现。下面是正确的代码

if __name__ == '__main__':
  applicationName = "DSS POS"
  # Initialization of the Notification library
  if not pynotify.init(applicationName):
   sys.exit(1)         

  flagContinous = True
  timeout = 5
  # This loop will continously keep the application in the background
  while flagContinous:
   time.sleep(timeout)
   runWorks()
  # After 30 seconds, "hello, world" will be printed  
我还使用了一个锁文件,这样脚本就不会运行多次

pid = str(os.getpid())
  pidfile = "/tmp/mydaemon.pid"

  # If we have a lock already block the program
  if os.path.isfile(pidfile):
    print "%s already exists, exiting" % pidfile
    sys.exit()
  else:
    file(pidfile, 'w').write(pid)
  # Do all the work
  applicationName = "DSS POS"
  # Initialization of the Notification library
  if not pynotify.init(applicationName):
   sys.exit(1)         

  # Controls for the application
  flagContinous = True
  timeout = 5
  # This loop will continously keep the application in the background
  while flagContinous:
   time.sleep(timeout)
   runWorks()
  # After 30 seconds, "hello, world" will be printed  

  # Release the file
  os.unlink(pidfile)

最好使用以下简单的守护程序脚本:


它做得很好

我在阅读之前就回答了这个问题。这就是你需要的,一个事件循环。然而,我会使用一个变量,一个非真变量,这样你就可以以一种干净的方式退出循环,我只是写了一个与这个答案相同的答案。我很高兴你自己找到了。我的一个想法是让
runWorks()
函数返回True或False来告诉循环是否退出(尽管如果你没有预料到你的程序会故意退出,这可能并不重要)。如果你能告诉我它与我的代码有多大的不同,那就太好了?感谢“os.fork()”起了作用。