How to run my function in thread every 5 minutes | Python |

Viewed 34

I am trying to write a code where my function should run every 5 minutes ON and OFF

Means like : first 5 minutes it will run and next 5 minutes will be on sleep and again run

Need to achieve using Threading

So that I will have control to handle the Thread killing as an when required.

I am trying to store the function return message , start time and end time to Mongo DB

My code :

import threading
import pymongo as pymongo
import datetime
import json

dbUrl = pymongo.MongoClient("mongodb://localhost:5600/")
dbName = dbUrl["ABC"]
dbCollectionName = dbName["Demo"]


def hello_world():
    global kill_the_running_thread
    while (not kill_the_running_thread):
        msg="Hello"
        note_start_time = datetime.datetime.now()
        print(msg)
        note_end_time   = datetime.datetime.now()
        dt = {msg,note_start_time,note_end_time}
        r = json.dumps(dt)
        loaded_r = json.loads(r)
        rec_id1 = dbCollectionName.insert_one(r)
        dt = {}

def main():

    global kill_the_running_thread
    kill_the_running_thread = False
    my_thread = threading.Thread(target=hello_world())
    my_thread.start()

    input("Press enter to kill the running thread : ")
    kill_the_running_thread = True

# Calling main
main()

When I am running my code getting below error

TypeError: Object of type set is not JSON serializable
Hello

Any solution is much appreciated !!!

0 Answers
Related