Pranesh64 commited on
Commit
5465bb9
verified
1 Parent(s): 7442d4f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +56 -10
app.py CHANGED
@@ -674,18 +674,64 @@ def send_notifications_for_events(new_events):
674
 
675
  total_sent = 0
676
 
677
- for uid, mail, unsubscribe_token in users:
 
 
678
 
679
- html = f"""
680
- <h2>馃摙 New BIP Events Alert</h2>
681
- <p>{len(new_events)} new events have been added:</p>
682
- {events_html}
683
- <hr>
684
- <a href="{HF_URL}?unsubscribe={unsubscribe_token}">Unsubscribe</a>
685
- """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
686
 
687
- if send_email(mail, subject, html):
688
- total_sent += 1
 
689
 
690
  cur.close()
691
  db.close()
 
674
 
675
  total_sent = 0
676
 
677
+ from concurrent.futures import ThreadPoolExecutor, as_completed
678
+ import threading
679
+ import time
680
 
681
+ send_lock = threading.Lock()
682
+ last_sent_time = 0
683
+
684
+
685
+ def rate_limited_send(mail, subject, html):
686
+ global last_sent_time
687
+
688
+ with send_lock:
689
+ now = time.time()
690
+
691
+ # 馃敟 STRICT: 1 mail per second globally
692
+ if now - last_sent_time < 1:
693
+ time.sleep(1 - (now - last_sent_time))
694
+
695
+ last_sent_time = time.time()
696
+
697
+ return send_email(mail, subject, html)
698
+
699
+
700
+ # ================= REPLACE LOOP =================
701
+
702
+ max_workers = 5
703
+ batch_size = 20
704
+ total_sent = 0
705
+
706
+ for i in range(0, len(users), batch_size):
707
+ batch = users[i:i + batch_size]
708
+
709
+ print(f"馃摝 Sending batch {i//batch_size + 1} ({len(batch)} users)")
710
+
711
+ with ThreadPoolExecutor(max_workers=max_workers) as executor:
712
+ futures = []
713
+
714
+ for uid, mail, unsubscribe_token in batch:
715
+
716
+ html = f"""
717
+ <h2>馃摙 New BIP Events Alert</h2>
718
+ <p>{len(new_events)} new events have been added:</p>
719
+ {events_html}
720
+ <hr>
721
+ <a href="{HF_URL}?unsubscribe={unsubscribe_token}">Unsubscribe</a>
722
+ """
723
+
724
+ futures.append(
725
+ executor.submit(rate_limited_send, mail, subject, html)
726
+ )
727
+
728
+ for future in as_completed(futures):
729
+ if future.result():
730
+ total_sent += 1
731
 
732
+ # 馃敟 COOL DOWN between batches
733
+ print("鈴革笍 Cooling down 3 sec...")
734
+ time.sleep(3)
735
 
736
  cur.close()
737
  db.close()