Skip to content

Commit

Permalink
update examples
Browse files Browse the repository at this point in the history
  • Loading branch information
Paillat-dev committed Oct 3, 2024
1 parent 21b0cbd commit 22adfaf
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 29 deletions.
40 changes: 20 additions & 20 deletions examples/simple.py
Original file line number Diff line number Diff line change
@@ -1,49 +1,49 @@
# -*- coding: utf-8 -*-
from aiocron import crontab
from aiocron import asyncio
import asyncio
import logging

logging.basicConfig()
logging.basicConfig(level=logging.DEBUG)

loop = asyncio.get_event_loop()
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)


@crontab("* * * * * */3")
@crontab("* * * * * */3", loop=loop)
def mycron():
print("function")


@crontab("* * * * * */2", start=False)
@crontab("* * * * * */2", start=False, loop=loop)
def mycron2(i):
if i == 2:
raise ValueError(i)
return "yielded function (%i)" % i

return f"yielded function ({i})"

@asyncio.coroutine
def main():
cron = crontab("* * * * * */2")
async def main():
cron = crontab("* * * * * */2", loop=loop)
for i in range(3):
try:
yield from cron.next()
await cron.next()
except Exception:
pass
else:
print("yielded (%i)" % i)
print(f"yielded ({i})")

for i in range(3):
try:
res = yield from mycron2.next(i)
res = await mycron2.next(i)
except Exception as e:
print(repr(e))
else:
print(res)


loop.run_until_complete(main())
if __name__ == "__main__":
try:
loop.run_until_complete(main())
finally:
loop.close()

"""
Will print:
Expected output (may vary slightly due to timing):
yielded (0)
function
Expand All @@ -53,5 +53,5 @@ def main():
yielded function (0)
function
yielded function (1)
yielded function (2)
"""
ValueError(2)
"""
23 changes: 14 additions & 9 deletions examples/threaded.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,20 @@
class CronThread(threading.Thread):
def __init__(self):
super(CronThread, self).__init__()
self.loop = None
self.start()
time.sleep(0.1)
time.sleep(0.1) # Give time for the loop to start

def run(self):
self.loop = asyncio.new_event_loop()
asyncio.set_event_loop(self.loop)
self.loop.run_forever()
self.loop.close()

def stop(self):
self.loop.call_soon_threadsafe(self.loop.stop)
self.join()
if self.loop:
self.loop.call_soon_threadsafe(self.loop.stop)
self.join()
self.loop.close()

def crontab(self, *args, **kwargs):
kwargs["loop"] = self.loop
Expand All @@ -30,11 +32,14 @@ def crontab(self, *args, **kwargs):


@cron.crontab("* * * * * *")
@asyncio.coroutine
def run():
yield from asyncio.sleep(0.1)
async def run():
await asyncio.sleep(0.1)
print("It works")


asyncio.get_event_loop().run_forever()
cron.stop()
# Run for a short time then stop
try:
time.sleep(5) # Let it run for 5 seconds
finally:
cron.stop()
print("Cron stopped")

0 comments on commit 22adfaf

Please sign in to comment.