Skip to content

Commit ecc28a9

Browse files
authored
Merge pull request #1370 from quartata/master
Use asyncio Tasks
2 parents 6a1c985 + 986e8dd commit ecc28a9

File tree

7 files changed

+65
-55
lines changed

7 files changed

+65
-55
lines changed

chatcommands.py

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,8 @@
1515
from parsing import *
1616
from spamhandling import handle_spam
1717
from gitmanager import GitManager
18+
from tasks import Tasks
1819
import threading
19-
from threading import Thread
2020
import random
2121
import requests
2222
import os
@@ -687,10 +687,7 @@ def status():
687687
# noinspection PyIncorrectDocstring
688688
@command(privileged=True)
689689
def stopflagging():
690-
t_metasmoke = Thread(name="stop_autoflagging", target=Metasmoke.stop_autoflagging,
691-
args=())
692-
t_metasmoke.start()
693-
690+
Tasks.do(Metasmoke.stop_autoflagging)
694691
return "Request sent..."
695692

696693

classes/feedback.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
import threading
21
from metasmoke import Metasmoke
2+
from tasks import Tasks
33

44

55
class Feedback:
@@ -18,9 +18,7 @@ def send(self, url, msg):
1818

1919
@staticmethod
2020
def send_custom(type, url, msg):
21-
threading.Thread(name="metasmoke feedback send on " + url,
22-
target=Metasmoke.send_feedback_for_post,
23-
args=(url, type, msg.owner.name, msg.owner.id, msg._client.host,)).start()
21+
Tasks.do(Metasmoke.send_feedback_for_post, url, type, msg.owner.name, msg.owner.id, msg._client.host)
2422

2523

2624
TRUE_FEEDBACKS = {

deletionwatcher.py

Lines changed: 7 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,13 @@
66
import websocket
77
# noinspection PyPackageRequirements
88
from bs4 import BeautifulSoup
9-
from threading import Thread
109
from urllib.parse import urlparse
1110
import chatcommunicate
1211
import metasmoke
1312
from globalvars import GlobalVars
1413
import datahandling
1514
from parsing import fetch_post_id_and_site_from_url
15+
from tasks import Tasks
1616

1717

1818
# noinspection PyClassHasNoInit,PyBroadException,PyMethodParameters
@@ -52,9 +52,7 @@ def check_websocket_for_deletion(self, post_site_id, post_url, timeout):
5252
try:
5353
a = ws.recv()
5454
except websocket.WebSocketTimeoutException:
55-
t_metasmoke = Thread(name="metasmoke send deletion stats",
56-
target=metasmoke.Metasmoke.send_deletion_stats_for_post, args=(post_url, False))
57-
t_metasmoke.start()
55+
Tasks.do(metasmoke.Metasmoke.send_deletion_stats_for_post, post_url, False)
5856
return False
5957
if a is not None and a != "":
6058
try:
@@ -66,18 +64,12 @@ def check_websocket_for_deletion(self, post_site_id, post_url, timeout):
6664
d = json.loads(json.loads(a)["data"])
6765
except:
6866
continue
69-
if d["a"] == "post-deleted" and str(d["qId"]) == question_id \
70-
and ((post_type == "answer" and "aId" in d and str(d["aId"]) == post_id) or
71-
post_type == "question"):
67+
if d["a"] == "post-deleted" and str(d["qId"]) == question_id:
68+
if (post_type == "answer" and "aId" in d and str(d["aId"]) == post_id) or post_type == "question":
69+
Tasks.do(metasmoke.Metasmoke.send_deletion_stats_for_post, post_url, True)
70+
return True
7271

73-
t_metasmoke = Thread(name="metasmoke send deletion stats",
74-
target=metasmoke.Metasmoke.send_deletion_stats_for_post, args=(post_url, True))
75-
t_metasmoke.start()
76-
return True
77-
78-
t_metasmoke = Thread(name="metasmoke send deletion stats",
79-
target=metasmoke.Metasmoke.send_deletion_stats_for_post, args=(post_url, False))
80-
t_metasmoke.start()
72+
Tasks.do(metasmoke.Metasmoke.send_deletion_stats_for_post, post_url, False)
8173
return False
8274

8375
@classmethod

metasmoke.py

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,6 @@ def init_websocket():
6767

6868
@staticmethod
6969
def check_last_pingtime():
70-
threading.Timer(30, Metasmoke.check_last_pingtime).start()
7170
now = datetime.utcnow()
7271
errlog = open('errorLogs.txt', 'a', encoding="utf-8")
7372
if GlobalVars.metasmoke_last_ping_time is None:
@@ -265,7 +264,6 @@ def send_status_ping():
265264
log('info', "Metasmoke location not defined; not sending status ping")
266265
return
267266

268-
threading.Timer(60, Metasmoke.send_status_ping).start()
269267
metasmoke_key = GlobalVars.metasmoke_key
270268

271269
try:
@@ -347,7 +345,7 @@ def stop_autoflagging():
347345
data=json.dumps(payload), headers=headers)
348346

349347
@staticmethod
350-
def send_statistics(should_repeat=True):
348+
def send_statistics():
351349
GlobalVars.posts_scan_stats_lock.acquire()
352350
if GlobalVars.post_scan_time != 0:
353351
posts_per_second = GlobalVars.num_posts_scanned / GlobalVars.post_scan_time
@@ -367,6 +365,3 @@ def send_statistics(should_repeat=True):
367365
if GlobalVars.metasmoke_host is not None:
368366
requests.post(GlobalVars.metasmoke_host + "/statistics.json",
369367
data=json.dumps(payload), headers=headers)
370-
371-
if should_repeat:
372-
threading.Timer(600, Metasmoke.send_statistics).start()

spamhandling.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
import regex
1414
from classes import Post, PostParseError
1515
from helpers import log
16+
from tasks import Tasks
1617

1718

1819
# noinspection PyMissingTypeHints
@@ -127,12 +128,10 @@ def handle_spam(post, reasons, why):
127128
post.user_name.strip(), poster_url, shortened_site)
128129
username = post.user_name.strip()
129130

130-
t_metasmoke = Thread(name="metasmoke send post",
131-
target=metasmoke.Metasmoke.send_stats_on_post,
132-
args=(post.title_ignore_type, post_url, reasons, post.body, username,
133-
post.user_link, why, post.owner_rep, post.post_score,
134-
post.up_vote_count, post.down_vote_count))
135-
t_metasmoke.start()
131+
Tasks.do(metasmoke.Metasmoke.send_stats_on_post,
132+
post.title_ignore_type, post_url, reasons, post.body, username,
133+
post.user_link, why, post.owner_rep, post.post_score,
134+
post.up_vote_count, post.down_vote_count)
136135

137136
log('debug', GlobalVars.parser.unescape(s).encode('ascii', errors='replace'))
138137
datahandling.append_to_latest_questions(post.post_site, post.post_id, post.title)

tasks.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import asyncio
2+
import threading
3+
4+
5+
class Tasks:
6+
loop = asyncio.new_event_loop()
7+
8+
@classmethod
9+
def _run(cls):
10+
try:
11+
cls.loop.run_forever()
12+
finally:
13+
cls.loop.close()
14+
15+
@classmethod
16+
def do(cls, func, *args, **kwargs):
17+
cls.loop.call_soon(lambda: func(*args, **kwargs))
18+
cls.loop._write_to_self()
19+
20+
@classmethod
21+
def later(cls, func, *args, after=None, **kwargs):
22+
cls.loop.call_later(after, lambda: func(*args, **kwargs))
23+
cls.loop._write_to_self()
24+
25+
@classmethod
26+
def periodic(cls, func, *args, interval=None, **kwargs):
27+
@asyncio.coroutine
28+
def f():
29+
while True:
30+
yield from asyncio.sleep(interval)
31+
func(*args, **kwargs)
32+
33+
cls.loop.create_task(f())
34+
cls.loop._write_to_self()
35+
36+
37+
threading.Thread(name="tasks", target=Tasks._run, daemon=True).start()

ws.py

Lines changed: 11 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@
1616
# noinspection PyPackageRequirements
1717
import websocket
1818
import getpass
19-
import threading
2019
from threading import Thread
2120
import traceback
2221
from bodyfetcher import BodyFetcher
@@ -34,6 +33,7 @@
3433
# noinspection PyPackageRequirements
3534
from tld.utils import update_tld_names, TldIOError
3635
from helpers import log
36+
from tasks import Tasks
3737

3838
import chatcommands
3939

@@ -121,26 +121,19 @@
121121

122122
# noinspection PyProtectedMember
123123
def check_socket_connections():
124-
while True:
125-
time.sleep(90)
126-
127-
for client in chatcommunicate._clients.values():
128-
if client.last_activity:
129-
if (datetime.utcnow() - client.last_activity).total_seconds() >= 60:
130-
os._exit(10)
131-
132-
133-
Thread(name="check socket connections", target=check_socket_connections, daemon=True).start()
124+
for client in chatcommunicate._clients.values():
125+
if client.last_activity and (datetime.utcnow() - client.last_activity).total_seconds() >= 60:
126+
os._exit(10)
134127

135128

136129
# noinspection PyProtectedMember
137-
def restart_automatically(time_in_seconds):
138-
time.sleep(time_in_seconds)
139-
Metasmoke.send_statistics(False) # false indicates not to auto-repeat
130+
def restart_automatically():
131+
Metasmoke.send_statistics()
140132
os._exit(1)
141133

142134

143-
Thread(name="auto restart thread", target=restart_automatically, args=(21600,)).start()
135+
Tasks.periodic(check_socket_connections, interval=90)
136+
Tasks.later(restart_automatically, after=21600)
144137

145138
log('info', GlobalVars.location)
146139
log('info', GlobalVars.metasmoke_host)
@@ -155,14 +148,13 @@ def restart_automatically(time_in_seconds):
155148
elif "first_start" in sys.argv and not GlobalVars.on_master:
156149
chatcommunicate.tell_rooms_with("debug", GlobalVars.s_reverted)
157150

158-
Metasmoke.send_status_ping() # This will call itself every minute or so
159-
threading.Timer(600, Metasmoke.send_statistics).start()
151+
Tasks.periodic(Metasmoke.send_status_ping, interval=60)
152+
Tasks.periodic(Metasmoke.send_statistics, interval=600)
153+
Tasks.periodic(Metasmoke.check_last_pingtime, interval=30)
160154

161155
metasmoke_ws_t = Thread(name="metasmoke websocket", target=Metasmoke.init_websocket)
162156
metasmoke_ws_t.start()
163157

164-
Metasmoke.check_last_pingtime() # This will call itself every 10 seconds or so
165-
166158
while True:
167159
try:
168160
a = ws.recv()

0 commit comments

Comments
 (0)