2017  Kodetalk | Feedback | Privacy Policy | Terms | About
userimage

How to trigger/schedule a method for every specific day using java code

In my project i want to schedule a task using java code and it should run on specific day. Means i want that code to execute on Monday only if i schedule for Monday. How can i do so.

userimage

try below code and do change based on your requirement of the day i have created for trigger the task.

  1. package com.test.scheduler;
  2. import java.time.DayOfWeek;
  3. import java.time.LocalDate;
  4. import java.util.concurrent.Executors;
  5. import java.util.concurrent.ScheduledExecutorService;
  6. import java.util.concurrent.TimeUnit;
  7. public class SchedulerForTriggerOnWednesday implements Runnable {
  8. @Override
  9. public void run() {
  10. if (LocalDate.now().getDayOfWeek().getValue() == DayOfWeek.WEDNESDAY.getValue()) {
  11. System.out.println("Run on Wednesday only...");
  12. } else {
  13. System.out.println("Run on Other only...");
  14. }
  15. }
  16. public static void main(String[] args) {
  17. ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
  18. executorService.scheduleAtFixedRate(new SchedulerForTriggerOnWednesday(), 0, 1, TimeUnit.DAY);
  19. }
  20. }

Hope this will help you to make your scheduler work.

Answer is