| Ligne 143 : |
Ligne 143 : |
| | == Add scheduler task == | | == Add scheduler task == |
| | The {{fname|on_tasks_create}} parameter of the call {{fname|1=din.setup( setup=None, loop=loop, on_tasks_create=create_tasks )}} allow the ''user_code'' to add one or more asynchronous tasks. | | The {{fname|on_tasks_create}} parameter of the call {{fname|1=din.setup( setup=None, loop=loop, on_tasks_create=create_tasks )}} allow the ''user_code'' to add one or more asynchronous tasks. |
| | + | |
| | + | One of the most interesting task to create is a scheduler! |
| | + | |
| | + | A scheduler like [https://github.com/mchobby/micropython-aioschedule micropython-aioschedule] can do much more than executing a job every minute or so. A scheduler can execute a task every day at a given time, or every Tuesday, every Saturday, a given date, etc. |
| | + | |
| | + | The following code snippet shows the schedule of two job... jobs defined as '''async functions''' because aioschedule is asynchronous implementation. |
| | + | |
| | + | <syntaxhighlight lang="python"> |
| | + | import schedule |
| | + | |
| | + | # === Define & schedule Jobs ================== |
| | + | async def job_relay2(): |
| | + | global din |
| | + | din.rel2.on() |
| | + | din.leds[1].on() |
| | + | await asyncio.sleep(30) # Wait 30 Sec |
| | + | din.leds[1].off() |
| | + | din.rel2.off() |
| | + | |
| | + | |
| | + | async def job_toggle_led( led_idx ): # Job with parameter |
| | + | global din |
| | + | din.leds[led_idx].toggle() |
| | + | |
| | + | schedule.every(1).minutes.do( job_relay2 ) |
| | + | schedule.every(3).seconds.do( job_toggle_led, 2 ) # Toggle led 2 of 0..3 |
| | + | schedule.every(7).seconds.do( job_toggle_led, 3 ) # Toggle led 3 of 0..3 |
| | + | </syntaxhighlight> |
| | + | |
| | + | Now, let's use the {{fname|on_tasks_create}} parameter to create a new asyncio task that runs the scheduler. |
| | + | |
| | + | <syntaxhighlight lang="python"> |
| | + | def create_tasks( async_evloop ): |
| | + | # new task to register |
| | + | scheduler_task = async_evloop.create_task( schedule.run_forever() ) |
| | + | |
| | + | din.setup( setup=None, loop=loop, on_tasks_create=create_tasks ) |
| | + | </syntaxhighlight> |
| | + | |
| | + | '''Now, glue the snipset into the final code:''' |
| | + | |
| | + | The content here below can be found in |