How to schedule a task in Java?

In Java scheduling a task to run on fix intervals is quite simple.  Here is the code to create a scheduler 

 

		BasicThreadFactory schedulerFactory = new BasicThreadFactory.Builder()
			     .namingPattern("scheduler-%d").build();
		ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(schedulerFactory);
		// initial delay = 1 minute, and then each 30 minutes
		scheduler.scheduleWithFixedDelay(new Runnable() {
			
			@Override
			public void run() {
				// TODO do whatever you want
				
			}
		}, 1, 1, TimeUnit.MINUTES);

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.