micropython的简单cron。
micropython-scron的Python项目详细描述
micropython的简单cron
simplecron是一个基于时间的任务调度程序,其灵感来自于 用于unix系统的cron程序。
该软件在micropython 1.10(esp32,esp8266)和python 3.5下进行了测试。
如何使用这个库:
- 以精确定义的间隔运行任何任务
- 在程序运行时删除和添加任务。
- 运行任务一定次数和更多次。
要求:
- 安装micropython的板(v1.10)
- 电路板必须支持硬件定时器。
安装
您可以使用upip安装:
importupipupip.install("micropython-scron")
或
micropython -m upip install -p modules micropython-scron
您还可以克隆此存储库,然后手动安装:
git clone https://github.com/fizista/micropython-scron.git
cd ./micropython-scron
./flash-src.sh
ESP8266
此处理器上的库必须编译为二进制代码。
这需要micropython交叉编译器。
如果已经有mpy cross命令可用,则运行bash脚本:
./compile.sh
然后将库上载到设备,例如使用以下脚本:
./flash-byte.sh
重要!更好的解决方案是将此模块集成到固件中。 这个模块占用的RAM要少得多。
为此,请将scron
模块复制到micropython/ports/esp8266/modules
。
然后编译源代码,并将它们上传到您的设备。
简单示例
每秒运行的简单代码:
fromscron.weekimportsimple_cron# OR# SimpleCRON single-class library, with minimal recursion depth.# This is mainly for ESP8266, because we have very few possible recursions.fromscron.cweekimportsimple_cron# Depending on the device, you need to add a task that# will be started at intervals shorter than the longest# time the timer can count.# esp8266 about 5 minutes# esp32 - for processor ESP32D0WDQ6, the problem did not occursimple_cron.add('null',lambda*a,**k:None,seconds=0,minutes=range(0,59,5),removable=False)simple_cron.add('helloID',lambda*a,**k:print('hello'))simple_cron.run()
代码,每周日12:00.00激活一次:
simple_cron.add('Sunday12.00',lambda*a,**k:print('wake-up call'),weekdays=6,hours=12,minutes=0,seconds=0)
每秒钟:
simple_cron.add('Every second minute',lambda*a,**k:print('second call'),minutes=range(0,59,2),seconds=0)
其他使用示例可以在“examples”目录中找到。
如何使用
在代码中的某个地方,您必须添加以下代码, 从那时起,simplecron就可以使用了。
fromscron.weekimportsimple_cronsimple_cron.run()# You have to run it once. This initiates the SimpleCRON action,# and reserve one timmer.
添加正在使用的任务:
simple_cron.add(<callback_id_string>,<callback>,...)
回拨
回调示例:
defsome_counter(scorn_instance,callback_name,pointer,memory):if'counter'inmemory:memory['counter']+=1else:memory['counter']=1
其中:
scorn_instance
-simpleron实例,在本例中为scron.weekend.simple椆croncallback_name
-回调idpointer
-这是运行任务的时间指示器。 例:(6,13,5,10)。这是(星期日,下午1点,分钟5,秒10)memory
-在所有调用之间,此特定回调的共享内存。 默认情况下这是一本字典。
如果由于某种原因正在运行的回调引发异常, 然后可以使用特殊功能处理此事件。 默认的异常处理函数是print()。
要为回调异常添加新的处理函数,只需将它们添加到下面的列表:
simple_cron.callback_exception_processors(processor_function)
其中:
processor_function is function(exception_instance)
重要提示:
- 如果一个任务需要很长时间,它会阻止其他任务的执行!
- 如果在给定的时间有几个函数要运行,那么它们是 开始时没有特定的顺序。
- 如果时间已更改(与网络的时间同步,
运行
simple_cron._sync_time()
函数, 这将设定一个特定的时间点。如果没有这个设置, 可能会发生某些回调无法启动的情况。
未测试的内容:
- 睡眠中的简单电子操作
如何测试
首先安装以下组件:
git clone https://github.com/fizista/micropython-scron.git
cd micropython-scron/
micropython -m upip install -p modules micropython-unittest
micropython -m upip install -p modules micropython-time
然后运行测试:
./run_tests.sh
直接在设备上测试:
pip install pyserial adafruit-ampy ./run_tests_esp.sh upload_combined ./run_tests_esp.sh run /dev/ttyUSB0 ./run_tests_esp.sh upload ./run_tests_esp.sh run /dev/ttyUSB0