DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How To Prioritize Your Workload: 9 Steps and Tips
  • 8 Must-Have Project Reports You Can Use Today
  • Dynamically Schedule the Same Task with Multiple Cron Expression Using Spring Boot
  • The Impact of AI Agents on Modern Workflows

Trending

  • Event-Driven Architectures: Designing Scalable and Resilient Cloud Solutions
  • Java Virtual Threads and Scaling
  • Unlocking AI Coding Assistants Part 2: Generating Code
  • Evolution of Cloud Services for MCP/A2A Protocols in AI Agents

How to Schedule a Task to Run in an Interval

In this tutorial, you'll learn three ways to run a task in the background during an interval.

By 
Abhijeet Sutar user avatar
Abhijeet Sutar
·
Apr. 03, 14 · Tutorial
Likes (9)
Comment
Save
Tweet
Share
140.6K Views

Join the DZone community and get the full member experience.

Join For Free

There is often a need in applications to run some particular task in the background to accomplish some work in an interval. The example can be, service running in the background for cleanup of application just like, we have the Java Garbage collection.

In this article, I will show you 3 different ways to achieve this

They are as follows

  • using simple thread
  • using TimerTask
  • using ScheduledExecutorService

Using Simple Thread

This is very simple, which creates the simple thread puts it run in forever with use of while loop and makes use of sleep method to put the interval between running.

This is simply fast and quick way to achieve it

Following is code for this.

public class Task1 {
public static void main(String[] args) {
  // run in a second
  final long timeInterval = 1000;
  Runnable runnable = new Runnable() {
  public void run() {
    while (true) {
      // ------- code for task to run
      System.out.println("Hello !!");
      // ------- ends here
      try {
       Thread.sleep(timeInterval);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      }
    }
  };
  Thread thread = new Thread(runnable);
  thread.start();
  }
}

Using the Timer and TimerTask

Previous method we saw was very quickest possible, but it lacks some functionality

This has much more benefits than previous they are as follows

  • control over when start and cancel task
  • first execution can be delayed if wanted, provides useful

In this we use, Timer class for scheduling purpose and TimerTask is used for enclosing task to be executed inside its run() method.

Timer instance can be shared to schedule the multiple task and it is thread-safe.

When Timer constructor is called , it creates one thread and this single thread is used any scheduling of task.

For our purpose, we use Timer#scheduleAtFixedRate

Following code shows the use of Timer and TimerTask

import java.util.Timer;
import java.util.TimerTask;
public class Task2 {
  public static void main(String[] args) {
    TimerTask task = new TimerTask() {
      @Override
      public void run() {
        // task to run goes here
        System.out.println("Hello !!!");
      }
    };
    Timer timer = new Timer();
    long delay = 0;
    long intevalPeriod = 1 * 1000; 
    // schedules the task to be run in an interval 
    timer.scheduleAtFixedRate(task, delay,
                                intevalPeriod);
  } // end of main
}
These classes are classes existed from the JDK 1.3.

Using ScheduledExecutorService

This is introduced in java.util.concurrent from Java SE 5 as Concurrency utilities. This is preferred way to achieve the goal.

It provides following benefits as compared to previous solutions

  • pool of threads is used to execute as compared TImer`s single thread
  • Provides the flexibility for delaying first execution
  • Provides nice conventions for providing the time intervals

Following code shows use of same,

 In this, we use ScheduledExecutorService#scheduleAtFixedRate as shown , it takes param as runnable which particular piece of code we want to run , initialdelay for first execution

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class Task3 {
  public static void main(String[] args) {
    Runnable runnable = new Runnable() {
      public void run() {
        // task to run goes here
        System.out.println("Hello !!");
      }
    };
    ScheduledExecutorService service = Executors
                    .newSingleThreadScheduledExecutor();
    service.scheduleAtFixedRate(runnable, 0, 1, TimeUnit.SECONDS);
  }
}
Task (computing) Schedule (computer science)

Published at DZone with permission of Abhijeet Sutar, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How To Prioritize Your Workload: 9 Steps and Tips
  • 8 Must-Have Project Reports You Can Use Today
  • Dynamically Schedule the Same Task with Multiple Cron Expression Using Spring Boot
  • The Impact of AI Agents on Modern Workflows

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!