How to schedule a task in OCaml?

北城余情 提交于 2019-12-12 09:27:44

问题


I have a task need to be done every 4 hours or once a day.

In Java, it has quartz or spring or timer.

But in OCaml, how do I do that? Any good lib for that?


回答1:


I don't know any library to do that, but I think you can easily implement that kind of behavior using the Lwt library.

Little example, to print Hello world every 4 hours :

let rec hello () = 
    Lwt.bind (Lwt_unix.sleep 14400.) 
       (fun () -> print_endline "Hello, world !"; hello ())
Lwt.async (hello)

The Lwt.async function call the function given (here, hello) in an asynchronous light weight thread, so you're free to do other stuff in your program. As long as your program doesn't exit, "Hello world" will be printed every 4 hours.

If you want to be able to stop it, you can also launch the thread like this instead of Lwt.async :

let a = hello ()

And then, to stop the thread :

Lwt.cancel a

Be aware that Lwt.cancel throws a "Lwt.canceled" exception !

Then, to be able to launch a task at a particular time of day, I can only encourage you to use functions from the Unix module, like localtime and mktime.



来源:https://stackoverflow.com/questions/17091116/how-to-schedule-a-task-in-ocaml

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!