Call function after specific time interval in android using java

You are currently viewing Call function after specific time interval in android using java
call method after certain time interval in android java

Welcome back coders In this article we will touch very basic and interesting topic on how to call an function after specific time. If you are looking for how to call an function in certain time interval when app is running in background then have you are on the accurate location .

Let’s get started 

Using Handler class and Runnable Interface

We know that when we want to run any process or method for one-time or repeated execution by a Timer  we need to use threading mechanism.

With the help of Handler class and Runnable Interface we can achieve the threading mechanism. 

Let’s create the Object of Hander class and create Runnable implementer 

				
					Handler handler = new Handler();
Runnable runnable ;
int delay = 5000;
				
			

How to run method after specific time

Here is the code  which will allow the method to run in the background. In Our case we are calling the method when activity is in onPause state.

				
					protected void onPause(){
        handler.postDelayed(runnable = new Runnable() {
            @Override
            public void run() {
                handler.postDelayed(runnable, delay);
                methodToRun();
            }
        },delay);
        super.onPause();
    }
				
			

And here we are, this is how we can call any method after specific time interval. We hope this simple and clean code is useful to achieve your next goal.

Thank you.

Leave a Reply