最近看师父写的项目(项目是erlang项目,rebar3管理)中用到了Erlcron模块,仔细看了下是做定时任务用的,使用时只需要在项目主配置文件sys.config中配置相关定时任务的参数,然后整个项目启动是就可以实现需要定时的功能。
下面我们来看一下
这是师父在项目说明文档中写的使用例子
Job = {{weekly, thu, {2, am}}, {io, fwrite, ["It's 2 Thursday morning~n"]}}. erlcron:cron(Job).
这样就完成了一个定时任务,很简单,每周二的上午2点在控制台打印:"It's 2 Thursday morning" 这句话.
其中的job可以是这样的定义:
{{once, {3, 30, pm}},
{io, fwrite, ["Hello, world!~n"]}}
{{once, {12, 23, 32}},
{io, fwrite, ["Hello, world!~n"]}}
{{once, 3600},
{io, fwrite, ["Hello, world!~n"]}}
{{daily, {every, {23, sec}, {between, {3, pm}, {3, 30, pm}}}},
{io, fwrite, ["Hello, world!~n"]}}
{{daily, {3, 30, pm}},
fun() -> io:fwrite("It's three thirty~n") end}
{{daily, [{1, 10, am}, {1, 07, 30, am}]},
{io, fwrite, ["Bing~n"]}}
{{weekly, thu, {2, am}},
{io, fwrite, ["It's 2 Thursday morning~n"]}}
{{weekly, wed, {2, am}},
{fun() -> io:fwrite("It's 2 Wednesday morning~n") end}
{{weekly, fri, {2, am}},
{io, fwrite, ["It's 2 Friday morning~n"]}}
{{monthly, 1, {2, am}},
{io, fwrite, ["First of the month!~n"]}}
{{monthly, 4, {2, am}},
{io, fwrite, ["Fourth of the month!~n"]}}
我基本已经做过测试了,大家也可以自己写个定时任务测试下。
如何使用
当此项目作为依赖时
- 需要在主应用的rebar.config配置文件中添加上
{deps, [
......
{erlcron, {git, "git://github.com/simonxu72/erlcron", {branch, "master"}}}
......
]}
- .app.src文件中配置依赖
{applications,
[
......
erlcron,
......
]}
- sys.config中配置
[
{erlcron, [
{crontab, [
{{once, {3, 30, pm}}, {io, fwrite, ["Hello, world!~n"]}},
{{once, {12, 23, 32}}, {io, fwrite, ["Hello, world!~n"]}},
{{daily, {every, {23, sec}, {between, {3, pm}, {3, 30, pm}}}},
{io, fwrite, ["Hello, world!~n"]}}
]}
]}
].
4.主项目用rebar3 shell中启动就可以了
网友评论