0

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 !!!

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
yyy62103
  • 81
  • 5
  • 1
    You are trying to serialize a `set` object `dt` into `json` string. You can do something like `dt={"message":msg, "start_time": note_start_time, "end_time": note_end_time}` and it should work. – Bijay Regmi Sep 03 '22 at 06:16
  • 1
    And running your code every 5 minutes, there are several ways of achieving this. Either you can use a python block scheduler like this: https://github.com/agronholm/apscheduler or even use `while True:` to create infinite loop and call your main function `main()` inside that loop and sleep after every call with `time.sleep(6000)`. Another alternative would be to create cronjob with your python script and run it every 5 mins. – Bijay Regmi Sep 03 '22 at 06:18

0 Answers0