简体   繁体   中英

How can I run a function forever?

Im trying to run the listener function forever, for example I want any time there is new information available in the stream it updates on the list automatically. Any idea in how to do it would be appreciated.

class Notifications(Screen):
   notificationslist = ObjectProperty(None)

def listener(self, event = None):
       notifications_screen = self.manager.get_screen('notif')
       print(event.event_type)  # can be 'put' or 'patch'
       print(event.path)  # relative to the reference, it seems
       print(event.data)  # new data at /reference/event.path. None if deleted
       notifications = event.data
       if notifications.items() == None:
           return
       else:
           for key, value in notifications.items():
               thevalue = value
               notifications_screen.notificationslist.adapter.data.extend([value[0:17] + '\n' + value[18:]])
               print(thevalue)
               id = (thevalue[thevalue.index("(") + 1:thevalue.rindex(")")])
               print(id)

If you want a function to run forever but that does not block you from doing other functions, then you can use threads .

Here is an example with example_of_process that runs forever, and then the main program with time.sleep(3)

import threading
import time

def example_of_process():
    count = 0
    while True:
        print("count", count)
        count += 1
        time.sleep(1)

thread_1 = threading.Thread(target=example_of_process)
thread_1.daemon = True # without the daemon parameter, the function in parallel will continue even if your main program ends
thread_1.start()

# Now you can do anything else. I made a time sleep of 3s, otherwise the program ends instantly
time.sleep(3)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM