Raghu
Raghu

Reputation: 69

Avoid running same job by two EC2 instances

I am using APScheduler in decorator way to run jobs at certain intervals. The problem is that when below code is deployed in two EC2 instances then same job runs twice at same with difference in milliseconds.

My question is : How to avoid running same job by two EC2 instances at same time or Do I need to follow different code design pattern in this case. I want to run this job only once either by one of the severs.

from datetime import datetime
from apscheduler.schedulers.blocking import BlockingScheduler

sched = BlockingScheduler()
sched.start()    

@sched.scheduled_job('interval', id='my_job_id', hours=2)
def job_function():
  print("Hello World")

If you can share any locking mechanism examples it would be appreciable

Upvotes: 1

Views: 479

Answers (1)

Zeeshan
Zeeshan

Reputation: 117

You can use AWS-SDK/AWS-CLI by using AWS-SDK/AWS-CLI you can set

If instance_id = "your instance id"
 Write your code here

Now your cron will get execute on each instances you have and your code will be executed from that specific instance.

Upvotes: 0

Related Questions