Merge: doc: fixed some typos and other misc. corrections
[nit.git] / lib / popcorn / pop_tasks.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2016 Alexandre Terrasa <alexandre@moz-code.org>
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 # Popcorn threaded tasks
18 #
19 # Tasks allow you to execute code in another thread than the app listening loop.
20 # Useful when you want to run some tasks periodically.
21 #
22 # Let's say you want to purge the `downloads/` directory of your app every hour:
23 #
24 # ~~~nitish
25 # class PurgeTask
26 # super PopTask
27 #
28 # var dir: String
29 #
30 # redef fun main do
31 # loop
32 # dir.rmdir
33 # 3600.sleep
34 # end
35 # end
36 # end
37 #
38 # var app = new App
39 #
40 # # Register a new task
41 # app.register_task(new PurgeTask("downloads/"))
42 #
43 # # Add your handlers
44 # # app.use('/', new MyHandler)
45 #
46 # # Run the tasks
47 # app.run_tasks
48 #
49 # # Start the app
50 # app.listen("0.0.0.0", 3000)
51 # ~~~
52 module pop_tasks
53
54 import pop_handlers
55 import pthreads
56
57 # An abstract Popcorn task
58 #
59 # Redefine the `main` method to do something
60 #
61 # TODO provide a CRON-like syntax like SpringBoot?
62 abstract class PopTask
63 super Thread
64
65 redef fun main do return null
66 end
67
68 redef class App
69
70 # Tasks to run
71 var tasks = new Array[PopTask]
72
73 # Register a new task in `self`
74 fun register_task(task: PopTask) do tasks.add task
75
76 # Run all registered tasks
77 fun run_tasks do for task in tasks do task.start
78 end