3

I want a function to run every 5 minutes while the main program is still running.

I've found multiple posts on how to make a function run every few seconds but they don't seem to work for me.

This is my program:

from Read import getUser, getMessage
from Socket import openSocket, sendMessage
from Initialize import joinRoom, Console
from question import query_yes_no
from Settings import AIDENT
import string
import sched, time
import urllib.parse
import requests
import subprocess
import sys
import os 

s = openSocket()
joinRoom(s)

while True:
    try:
        try:
            readbuffer = s.recv(1024)
            readbuffer = readbuffer.decode()
            temp = readbuffer.split("\n")
            readbuffer = readbuffer.encode()
            readbuffer = temp.pop()
        except:
            temp = ""

        for line in temp:
            if line == "":
                break
            if "PING" in line and Console(line):
                msgg = (("PONG tmi.twitch.tv\r\n").encode())
                print(msgg)
                s.send(msgg)
                break
            user = getUser(line)
            message = getMessage(line)
            print (user + " > " + message)
            PMSG = "/w " + user + " "

            if "!ping" in message:
                sendMessage(s, "PONG ( i'm working fine )")


    except:
        pass

I need to run sendMessage() function every 5 minutes without interrupting main program.

Elis Byberi
  • 1,422
  • 1
  • 11
  • 20
Cyber_Star
  • 155
  • 1
  • 9

2 Answers2

5

You have use threading in case , where your main method will keep on exeuting in separate thread and repeater function will execute after every nth sec sample code would be like this :

import threading

def printit():
  threading.Timer(5.0, printit).start()
  print "Hello, World!"

printit()

Give it a try by your self .

coder3521
  • 2,608
  • 1
  • 28
  • 50
2

You should be using threads. This will create a thread, which simply executes your code and sleeps for 5 min. Instead of running your function, run the last two commands to create the thread and start it.

import threading
import time

def pong():
    while True:
         sendMessage(s, "PONG ( i'm working fine )")
         time.sleep(300)

t = threading.Thread(target=pong, args=(,))
t.start()
Chen A.
  • 10,140
  • 3
  • 42
  • 61