##language:zh #pragma section-numbers off ##含有章节索引导航的 ZPyUG 文章通用模板 <> ## 默许导航,请保留 <> = cron任务序列实现 = ##startInc == 需求 == [[http://groups.google.com/group/eurasia-users/browse_thread/thread/a31922b2fbdb9d4f|有沒有stackless tasklet 實現的 TaskQueue Server範例呢?]] - eurasia-users | Google 网上论坛 {{{ bawbaw reply-to eurasia-users@googlegroups.com to eurasia-users date Thu, Jul 16, 2009 at 19:14 }}} 在遊戲server 中,有些資料如能用TaskQueue進行輪詢處理的話就更省心呢,我有嘗試著實作,不過對於 tasklet 模式不能掌握,請問大家有沒有不錯的代碼可以供我參考使用呢… 像 GAE 中的 * http://googleappengine.blogspot.com/2009/06/new-task-queue-api-on-google-app-engine.html == tasklet == {{{ 沈崴 reply-to eurasia-users@googlegroups.com to eurasia-users date Fri, Jul 17, 2009 at 09:28 }}} 好像 tasklet 就是你要的東西, 你看看我理解得對不對: {{{#!python def foo(): for u in users: tasklet(sendmail)(to=u.email, subject='Hello ' + u.name, body='this is a message!') # tasklet 調用是直接返回的, 被調用者會在調度時執行 #... def sendmail(**args): mail.send_mail( 'from_me@example.com', args.get('to'), args.get('subject'), args.get('body')) #... stackless.run() # eurasia.mainloop() }}} ~ 不是這種的,這是馬上執行的,我是想要找一種,可以添加任務,設定每個任務每隔多久執行,以及設定運行一段時間候停止執行該任務有點像是 cron 那種,每隔一段時間重覆運行,但是又可以設定其運行時間,以及用程序方式去添加任務, == stackless::ProcessTask == 我来提供我昨天实作的,当服务重启时,会将之前的task 重新载入运行的 {{{ bawbaw reply-to eurasia-users@googlegroups.com to eurasia-users date Sun, Jul 19, 2009 at 19:47 }}} {{{#!python # encoding: utf-8 import os import sqlite3 import sha import pickle import sys from time import time, sleep from random import random from sqlite3 import IntegrityError from stackless import tasklet, schedule, channel def Sleep(sec): c = channel() while True: uid = sha.new('%s' % random()).hexdigest() try: cursor.execute( 'INSERT INTO hypnus VALUES (?, ?)', (uid, time() + sec) ) break except IntegrityError: continue channels[uid] = c c.receive() def tasklets(): while True: now = time() l = cursor.execute( 'SELECT id FROM hypnus WHERE timeout end_time:break#end task if time() < start_time:Sleep(start_time-time())#notstart ,sleep first if call_path == 'local': call_func(func, args = args) else: pass Sleep(sleep_time) #print '.', time() def get_task(self, name): '''get task by name''' self.get_db() #delete end task self.cursor.execute('delete from task where name = ? and end_time?', (now, )).fetchall() for rs in rows: rs = list(rs) rs[2] = pickle.loads(str(rs[2])) yield rs def clear_timeout_task(self): '''clear end task''' try: now = time() conn = sqlite3.connect(self.db_path) cursor = conn.cursor() cursor.execute('delete from task where end_time>]