ソースを参照

python scheduler update

swh 4 年 前
コミット
add4fe6b50

+ 35
- 0
src/kr/co/swh/lecture/python/scene5/scheduler/SchedulerModule.py ファイルの表示

@@ -0,0 +1,35 @@
1
+from apscheduler.jobstores.base import JobLookupError
2
+from apscheduler.schedulers.background import BackgroundScheduler
3
+import time
4
+
5
+class SchedulerTest:
6
+    def __init__(self):
7
+        self.sched = BackgroundScheduler()
8
+        self.sched.start()
9
+        self.job_id = ''
10
+
11
+    def __del__(self):
12
+        print("__del__ call")
13
+        self.shutdown()
14
+
15
+    def shutdown(self):
16
+        self.sched.shutdown()
17
+
18
+    def kill_scheduler(self, job_id):
19
+        try:
20
+            self.sched.remove_job(job_id)
21
+        except JobLookupError as err:
22
+            print("fail to stop Scheduler: {err}".format(err=err))
23
+            return
24
+
25
+    def hello(self, type, job_id):
26
+        print("%s Scheduler process_id[%s] : %d" % (type, job_id, time.localtime().tm_sec))
27
+
28
+    def scheduler(self, type, job_id):
29
+        print("{type} Scheduler Start".format(type=type))
30
+        if type == 'interval':
31
+            self.sched.add_job(self.hello, type, seconds=10, id=job_id, args=(type, job_id))
32
+        elif type == 'cron':
33
+            self.sched.add_job(self.hello, type, day_of_week='mon-sun',
34
+                               hour='0-23', second='*/1',
35
+                               id=job_id, args=(type, job_id))

+ 19
- 0
src/kr/co/swh/lecture/python/scene5/scheduler/cron-test.py ファイルの表示

@@ -0,0 +1,19 @@
1
+from SchedulerModule import SchedulerTest
2
+import time
3
+
4
+if __name__ == '__main__':
5
+    scheduler = SchedulerTest()
6
+    scheduler.scheduler('cron', "1")
7
+
8
+    count = 0
9
+    while True:
10
+        '''
11
+        count 제한할 경우 아래와 같이 사용
12
+        '''
13
+        print("Running main process")
14
+        time.sleep(1)
15
+        count += 1
16
+        if count == 10:
17
+            scheduler.kill_scheduler("1")
18
+            print("Kill cron Scheduler")
19
+            break

+ 19
- 0
src/kr/co/swh/lecture/python/scene5/scheduler/interval-test.py ファイルの表示

@@ -0,0 +1,19 @@
1
+from SchedulerModule import SchedulerTest
2
+import time
3
+
4
+if __name__ == '__main__':
5
+    scheduler = SchedulerTest()
6
+    scheduler.scheduler('interval', "2")
7
+
8
+    count = 0
9
+    while True:
10
+        '''
11
+        count 제한할 경우 아래와 같이 사용
12
+        '''
13
+        print("Running main process")
14
+        time.sleep(1)
15
+        count += 1
16
+        if count == 15:
17
+            scheduler.kill_scheduler("2")
18
+            print("Kill interval Scheduler")
19
+            break