Scheduled tasks with multiple servers - single poi

2019-04-24 18:27发布

问题:

We have a Spring + JPA web application. We use two tomcat servers that run both application and uses the same DB.

One of our application requirmemnt is to preform cron \ scheduled tasks.

After a short research we found that spring framework delivers a very straight forward solution to cron jobs, (Annotation based solution)

However since both tomcats running the same webapp - if we will use this spring's solution we will create a very problematic scenario where 2 crons are running at the same time (each on a different tomcat)

Is there any way to solve this issue? maybe this alternative is not good for our purpose?

thanks!

回答1:

As a general rule, you're going to want to save a setting to indicate that a job is running. Similar to how "Spring Batch" does the trick, you might want to create a table in your database simply for storing a job execution. You can choose to implement this however you'd like, but ultimately, your scheduled tasks should check the database to see if an identical task is already running, and if not, proceed with the task execution. Once the task has completed, update the database appropriately so that a future execution will be able to proceed.



回答2:

@kungfuters solution is certainly a better end goal, but as a simple first implementation, you could use a property to enable/disable the tasks, and only have the tasks run on one of the servers.