Quarkus does not provide support for EJB therefore you cannot rely on EJB Timers to schedule simple tasks. However, thanks to the extension quarkus-scheduler it is very simple to add this functionality.
Let’s create a simple project with Quarkus Maven plugin:
mvn io.quarkus:quarkus-maven-plugin:0.19.1:create \
-DprojectGroupId=com.sample \
-DprojectArtifactId=demo-scheduler \
-DclassName="com.sample.CountEndpoint" \
-Dpath="/count" \
-Dextensions="scheduler"
By the way, when the Quarkus CLI is available, you can use a simpler script to bootstrap your projects:
$ quarkus create-project --groupid=com.sample --artifactId=demo-scheduler --version=1.0 demo-scheduler --extension=scheduler
And here is a minimalist example of a Task which uses the @io.quarkus.scheduler.Scheduled annotation to run a task every 10 seconds:
package com.sample;
import java.util.concurrent.atomic.AtomicInteger;
import javax.enterprise.context.ApplicationScoped;
import io.quarkus.scheduler.Scheduled;
@ApplicationScoped
public class Counter {
private AtomicInteger counter = new AtomicInteger();
public int get() {
return counter.get();
}
@Scheduled(every="10s")
void increment() {
counter.incrementAndGet();
}
}
You can monitor the status of your Counter through a simple REST Endpoint:
package com.sample;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Path("/count")
public class CountEndpoint {
@Inject
Counter myCounter;
@GET
@Produces(MediaType.TEXT_PLAIN)
public String count() {
return "count: " + myCounter.get();
}
}
Using Cron based scheduler
Another alternative format for the @Scheduled annotation is to include a cron expression within it:
Here is an example, which schedules a Task every day at 8 AM:
@Scheduled(cron="0 0 8 * * ?")
void morningTask() {}