I am trying to write daemon service job in java. This service will run for every minute.
But I cannot implement this by using ExecutorService and I don't know if this is correct way. Below is my code snippet:
public void startService() {
try {
ExecutorService service = Executors.newFixedThreadPool(3);
for (;;) {
service.submit(new Service1()); // this will send some set of emails
service.submit(new Service2()); // this will send some set of emails
service.submit(new Service3()); // this will send some set of sms
}
service.shutdown(); // It says Unreachable code so when should i shutdown the service
service.awaitTermination(1, TimeUnit.MINUTES);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
First you need to look at ScheduledExecutorService and its implementations. This service allows you to schedule the jobs to run with pre-defined frequency. This is the short answer. As for implementation details there are too many unknowns to give you practical advice. Do you want your program to run in a container (Web or Application Server) or as Standalone with domain thread? are you running on Unix/Linux (So the Cron job scheduler can be used) or Windows? One of the scheduler options could be quartz-scheduler. I hope this helps.
Your for
loop does not have an ending condition: for(;;)
, and no break statement.
So all the code after this loop is if course unreachable.
You have to wait 1 minute inside the loop, not after (as the code after your looping will never be runned).
Keeping your synthax, I guess it should be:
for (;;) {
service.submit(new Service1()); // this will send some set of emails
service.submit(new Service2()); // this will send some set of emails
service.submit(new Service3()); // this will send some set of sms
service.shutdown();
service.awaitTermination(1, TimeUnit.MINUTES);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With