-
Notifications
You must be signed in to change notification settings - Fork 44
Intro to Tasks
Tasks are pieces of your program, split into small logical, reusable components.
These tasks may do things like periodic event processing, handling HTTP requests, handling thrift requests, working on items from a queue, waking up on an event, operating some ioloop, or something similar.
sparts
provides a set of common tasks for you to use directly or extend. If one doesn't seem to fit, extend the base VTask to implement whatever custom processing you need.
Here's a simple example of a service with an HTTP Server task (requires tornado installed):
from sparts.vservice import VService
from sparts.tasks.tornado import TornadoHTTPTask
TornadoHTTPTask.register()
VService.initFromCLI()
Running this emits:
> python myservice.py --http-port 8000
INFO:VService.TornadoHTTPTask:TornadoHTTPTask Server Started on 0.0.0.0 (port 8000)
INFO:VService.TornadoHTTPTask:TornadoHTTPTask Server Started on :: (port 8000)
DEBUG:MyService:All tasks started
And that's it! curl the webserver to verify:
> curl localhost:8000
Hello, world
Tasks can be subclassed to do all kinds of things. This one prints the current unix timestamp every second:
from sparts.tasks.periodic import PeriodicTask
class PrintClock(PeriodicTask):
INTERVAL = 1.0
def execute(self):
print time.time()
PrintClock.register()
from sparts.vservice import VService
VService.initFromCLI()
And the result:
DEBUG:VService:All tasks started
DEBUG:VService:VService Active. Awaiting graceful shutdown.
1376081805.08
1376081806.08
1376081807.08
1376081808.08
1376081809.08
1376081810.08
1376081811.08
Your service may require execution of sequential logic, without a runloop. This is common for tasks that depend on asynchronous event engines, like twisted, tornado, or gevent.
sparts supports "procedure" tasks, by declaring your task as LOOPLESS. This will allow you to override the initTask
, start
, and stop
hooks safely:
class MyProcedure(VTask):
LOOPLESS = True
def initTask(self):
self.logger.info("Initialize this task, open files, etc")
def start(self):
self.logger.info("Let's do some work once")
def stop(self):
self.logger.info("Clean up!")
MyProcedure.register()
VService.initFromCLI()
Running this produces the following:
> python demo/procedure.py --level INFO
INFO:VService.MyProcedure:Initialize this task, open files, etc
INFO:VService.MyProcedure:Let's do some real work
^CINFO:VService:signal -2 received
INFO:VService:Received graceful shutdown request
INFO:VService.MyProcedure:Clean up!
INFO:VService:Waiting for tasks to shutdown gracefully...
INFO:VService:Instance shut down gracefully
>
TBD