gevent动态随时添加任务

关于爬虫,有scrapy框架,也有requests加协程 协程 进程的方法。

相关的包很多,比如threading 、threadpool、multiprocessing,还有threadpoolexecutor、processpoolexecutor这两个。

协程gevent pool的用法和threadpool 很像,但关于使用协程我需要一个像threadpoolexecutor一样的强大方法,可以随时追加任务的。

 

# -*- coding: utf-8 -*-
import gevent,time,redis
from gevent.pool import Pool
from gevent.queue import JoinableQueue
from gevent import monkey
monkey.patch_all(time=True)
class GeventPoolExecutor(object):
    def __init__ (self,max_works):
        self._q = JoinableQueue()

        for i in range(max_works):
            gevent.spawn(self.worker)
        self._q.join()

    def worker(self):
        while True:
            fn= self._q.get()
            try:
                exec(fn)
            except Exception,e:
                print e
            finally:
                pass
                self._q.task_done()

    def submit(self,fn):
        self._q.put(fn)

def func(a,b):
    print a*10,b+100
    time.sleep(2)

if __name__=="__main__":                   ###测试

    gevent_pool_executor=GeventPoolExecutor(max_works=3)
    while(1):

        #print gevent_pool_executor.q.qsize()
        if gevent_pool_executor._q.qsize()<5:
            functionx=redis.Redis(host='127.0.0.1', port=6379, db=0).blpop('ceshi')[1]
       #functionx是一个字符串,内容例如为func(1,2),但是是个字符串,在worker中用exec来执行他 gevent_pool_executor.submit(functionx)
else: time.sleep(0.001)

 

另一个文件

#coding=utf-8

r=redis.Redis(host='127.0.0.1', port=6379, db=0)

for i in range(100,2000):

   #r.rpush('seeds', json.dumps(dictx))
r.rpush('ceshi','func(%s,%s)'%(i,i))
print 'func(%s,%s)'%(i,i)

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值