-
Notifications
You must be signed in to change notification settings - Fork 0
/
code_scheduler.py
74 lines (65 loc) · 3.23 KB
/
code_scheduler.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import sched
import time
import requests
import pytz
from main import run_my_code
from datetime import datetime, timedelta
s = sched.scheduler(time.time, time.sleep)
IST = pytz.timezone('Asia/Kolkata')
next_scheduled_time = ""
def check_connectivity():
try:
requests.get('http://www.google.com', timeout=5)
return True
except requests.ConnectionError:
return False
def schedule_tasks():
global next_scheduled_time
ist_now = datetime.now(IST)
current_time = ist_now.strftime("%H:%M:%S")
is_next_day = False
if check_connectivity():
if "08:30:00" < current_time < "08:45:00": # morning 8
scheduled_time = "08:50:00"
next_scheduled_time = (datetime.strptime("11:30:00", "%H:%M:%S") - datetime.strptime("08:30:00",
"%H:%M:%S")).total_seconds() / 60
elif "11:30:00" < current_time < "11:45:00": # morning 11
scheduled_time = "15:50:00"
next_scheduled_time = (datetime.strptime("15:30:00", "%H:%M:%S") - datetime.strptime("11:30:00",
"%H:%M:%S")).total_seconds() / 60
elif "15:30:00" < current_time < "15:45:00": # afternoon 3
scheduled_time = "15:50:00"
next_scheduled_time = (datetime.strptime("20:30:00", "%H:%M:%S") - datetime.strptime("15:30:00",
"%H:%M:%S")).total_seconds() / 60
elif "20:30:00" < current_time < "20:45:00": # night 8
scheduled_time = "20:50:00"
next_scheduled_time = (datetime.strptime("21:30:00", "%H:%M:%S") - datetime.strptime("20:30:00",
"%H:%M:%S")).total_seconds() / 60
elif "20:50:00" < current_time:
scheduled_time = "08:35:00"
ist_now = datetime.now(IST)
current_time = ist_now.strftime("%H:%M:%S")
scheduled_date_time = (datetime.now() + timedelta(days=1)).strftime('%Y-%m-%d') + f" {scheduled_time}"
next_scheduled_time = abs((datetime.strptime(scheduled_time, "%H:%M:%S") - datetime.strptime(current_time,
"%H:%M:%S")).total_seconds() / 60)
is_next_day = True
else:
return False
if not is_next_day:
scheduled_date_time = f"{ist_now.strftime('%Y-%m-%d')} {scheduled_time}"
s.enterabs(time.mktime(time.strptime(scheduled_date_time, "%Y-%m-%d %H:%M:%S")), 1, run_my_code, ())
return True
else:
return False
while True:
if schedule_tasks():
s.run()
print("Scheduled task executed.")
else:
time.sleep(300) # 300 seconds = 5 minutes
continue
now = datetime.now(IST)
next_minute = now.replace(second=0, microsecond=0) + timedelta(minutes=next_scheduled_time + 5)
time_remaining = (next_minute - now).total_seconds()
print(f"\nSleep Mode: {time_remaining} seconds")
time.sleep(time_remaining)