documentation/manual/working/commonGuide/schedule/ScheduledTasks.md
You can schedule sending messages to actors and executing tasks (functions or Runnable instances). You will get a Cancellable back that you can call cancel on to cancel the execution of the scheduled operation.
For example, to send a message to the testActor every 30 seconds:
Note: See [[Scala|ScalaPekko#Dependency-injecting-actors]] or [[Java|JavaPekko#Dependency-injecting-actors]] documentation about how to inject actors.
Similarly, to run a block of code 10 seconds from now, every minute:
Scala : @schedule-block-with-interval
Java : @schedule-block-with-interval
Or to run a block of code once 10 seconds from now:
Scala : @schedule-block-once
You can see the Pekko documentation to see other possible uses of the scheduler. See the documentation for pekko.actor.Scheduler for Scala or for Java.
Note: Instead of using the default
ExecutionContext, you can instead create aCustomExecutionContext. See documentation for Java or Scala. See the section about it below.
After defining the tasks as described above, you need to initialize them when your application starts.
When using Guice Dependency Injection, you will need to create and enable a module to load the tasks as eager singletons:
And then enable the module in your application.conf by adding the following line:
play.modules.enabled += "tasks.TasksModule"
As the task definitions are completely integrated with the Dependency Injection framework, you can also inject any necessary component inside of them. For more details about how to use Guice Dependency Injection, see [[Scala|ScalaDependencyInjection]] or [[Java|JavaDependencyInjection]] documentation.
When using compile-time Dependency Injection, you just need to start them in your implementation of BuiltInComponents:
This must then be used with your custom ApplicationLoader implementation. For more details about how to use compile-time Dependency Injection, see [[Scala|ScalaCompileTimeDependencyInjection]] or [[Java|JavaCompileTimeDependencyInjection]] documentation.
CustomExecutionContextYou should use a custom execution context when creating tasks that do sync/blocking work. For example, if your task is accessing a database using JDBC, it is doing blocking I/O. If you use the default execution context, your tasks will then block threads that are using to receive and handle requests. To avoid that, you should provide a custom execution context:
Scala : @custom-task-execution-context
Java : @custom-task-execution-context
Configure the thread pool as described in [[thread pools documentation|ThreadPools#Using-other-thread-pools]] using tasks-dispatcher as the thread pool name, and then inject it in your tasks:
Scala : @task-using-custom-execution-context
Java : @task-using-custom-execution-context
There are also modules that you can use to schedule tasks. Visit our [[module directory|ModuleDirectory#Task-Schedulers]] page to see a list of available modules.