I'm very new to working with asynchronous code, but I'm trying to create a basic app monitor with python. I want to integrate an asynchronous loop that performs some checks every 5 seconds.
from Foundation import NSObject, NSRunLoopimport objcfrom AppKit import NSWorkspace, NSWorkspaceDidActivateApplicationNotificationimport threadingimport asyncioclass ApplicationMonitor(NSObject): def init(self): self = objc.super(ApplicationMonitor, self).init() notification_center = NSWorkspace.sharedWorkspace().notificationCenter() notification_center.addObserver_selector_name_object_(self, self.application_activated, NSWorkspaceDidActivateApplicationNotification, None) self.start_asyncio_task() return self def start_asyncio_task(self): asyncio_thread = threading.Thread(target=self.run_asyncio_loop) asyncio_thread.start() def run_asyncio_loop(self): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) try: loop.run_until_complete(self.check_time()) finally: loop.run_until_complete(loop.shutdown_asyncgens()) async def check_time(self): while True: await asyncio.sleep(5) print("checking time") def application_activated(self): workspace = NSWorkspace.sharedWorkspace() frontmost_application = workspace.frontmostApplication() print("frontmost application: ", frontmost_application.localizedName())def main(): monitor = ApplicationMonitor.alloc().init() run_loop = NSRunLoop.currentRunLoop() run_loop.run()if __name__ == '__main__': main()
I expect the output to look something like this:
checking timefrontmost application: Firefoxfrontmost application: Codechecking timefrontmost application: Firefoxchecking timefrontmost application: Code
However, the output appears to get locked to the last visited application at the beginning of a new 5 second loop:
frontmost application: Firefoxfrontmost application: Codechecking timefrontmost application: Codefrontmost application: Codefrontmost application: Firefoxchecking timefrontmost application: Firefoxfrontmost application: Firefoxchecking timefrontmost application: Firefoxfrontmost application: Firefoxfrontmost application: Codefrontmost application: Firefoxfrontmost application: Codechecking time