Best way to implement an Agent in Django Applications
What I'm needing is something running in background, independently of web requests, continuously checking a specific table and performing some calculations. The term "agent" seems to fit better for this task, but I'm not sure if it's correct.
Any thought开发者_StackOverflows or ideas on how to implement this? The first thing that occurred me was a script being called by cron but I'm also not sure...
Thanks.
The most popular way these days is to use some sort of message queue, with a helper library like Celery. The way this works is that you will have a number of daemons running, listening on a message queue. In your application, you will add messages to the queue which will be picked up by the workers. This is pretty complex, but it's pretty fast.
However, it feels to me like completely overkill for your application. The cron
way of doing things is much simpler and less fragile. It also makes for easier debugging and testing of your code.
As a heretic side note, if your use case really is "check a specific table and perform some calculations that go into some other table", you could use a database trigger to do the work.
Try taking a look at Celery:
Celery is an open source asynchronous task queue/job queue based on distributed message passing. It is focused on real-time operation, but supports scheduling as well.
The execution units, called tasks, are executed concurrently on one or more worker nodes. Tasks can execute asynchronously (in the background) or synchronously (wait until ready).
I would think about using Cron tasks, but it depends on if use Unix or Windows systems.
The main advantage of Cron tasks is that it just runs a script, whatever language is used. So you can use shell script, python, php, etc.
Just to offer an alternative, the django-command-extensions app offers a job system that's pretty useful, especially if you have multiple jobs that you want to run. You still need to use cron
to trigger the jobs. See the docs
精彩评论