2014-05-09 37 views
-1

我想每120秒运行一段python代码。python什么是线程导入?

我尝试这样做:

class AppServerSvc : 

    def f(self): 
     # call f() again in 120 seconds 
     spider = FantasySerieaSpider() 
     settings = get_project_settings() 
     crawler = Crawler(settings) 
     crawler.signals.connect(reactor.stop, signal=signals.spider_closed) 
     crawler.configure() 
     crawler.crawl(spider) 
     crawler.start() 
     log.start() 
     reactor.run() # the script will block here until the spider_closed signal was sent 
     threading.Timer(120, f).start() 


if __name__ == '__main__': 
     AppServerSvc().f(); 

我得到了threading is not defined错误

这是我进口:

import pythoncom 
import win32serviceutil 
import win32service 
import win32event 
import servicemanager 
import socket 
from twisted.internet import reactor 
from scrapy.crawler import Crawler 
from scrapy import log, signals 
from FantasySeriea.spiders.spider import FantasySerieaSpider 
from scrapy.utils.project import get_project_settings 
from threading import Thread 

回答

4

,而不是(或除了):

from threading import Thread 

你想:

import threading 
+0

使用您的代码后,我得到'F'没有定义以为这是里面的函数班上。我应该说我必须说'self.f',会尝试 –

+0

否,'self.f()'产生一个无限循环,我该怎么做? –

+2

@MarcoDinatsoli'self.f',最后没有'()'。 – dano

4

您使用在你的代码threading.Timer但你从threadingThread导入,并把它插入到当前的命名空间。你想要的是导入整个模块:

import threading 

如果使用Thread,确保通过threading.Thread更换Thread。此外,你是在一个类中,所以你需要添加前缀self.f指类的成员:

threading.Timer(120, self.f).start() 
+0

+1谢谢..... –