How can I make a function to stop executing when it reaches a specific processing time.

//just make the example simple -
//the processing time is 3 seconds
...
while(true){
    counter++;
}
//after 3 seconds, continue to do the rest...
...
...
...
bernerackermanAsked:
Who is Participating?
 
muktajindalConnect With a Mentor Commented:
Try the approach in attached code snippet.
public class SchedulerTest {
	
	boolean active = true;
	int counter = 0;
	
    public static void main(String[] args) {
    	SchedulerTest schedulerTest = new SchedulerTest();
    	MyThread thread = schedulerTest.new MyThread();
    	thread.start();
    	try { Thread.sleep(1000); } catch (InterruptedException e) {}
    	schedulerTest.active = false;
    	System.out.println(schedulerTest.counter);
    }
 
    class MyThread extends Thread {
    	public void run() {
    		while (active) {
    			counter++;
    		}
    	}
    }
    
}

Open in new window

0
 
TrigunaCommented:
Use a Timer class. And schedule the task according to your wish.
For example:
java.util.Timer scheduler = new java.util.Timer();
scheduler.schedule(yourTask, firstTime, Period);

You can mentioned 3 seconds in period and do your task in the yourTask class.

Hope this helps.
0
 
SreejithGCommented:
Make the remaining part of ur function into a new function and use the function setTimeout(newFunc, 3000)
Using loop is not a good way.
0
Cloud Class® Course: C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

 
TrigunaCommented:
Or you can achieve this case using a Thread.
Just say Thread.sleep(3000). that is sleep for 3 seconds.
0
 
muktajindalCommented:
Making the thread sleep will cause your function not to do anything for those 3 seconds..
Your question is "how to make a function stop executing when it reaches a specific processing time", means you need to make your function do something for 3 seconds and then stop.
0
 
bernerackermanAuthor Commented:
If we put the Thread.sleep(3000) to the code, it only make the thread temporary stop 3 seconds. It will not kill the process and the number will continue displaying on the screen. Please see my example.

If I can do something like sreejithG suggestion i.e. setTimeout(printNumber(), 3000), then it will do. But I have no idea where the setTimeout method come from. How can I create the object to invoke this setTimeout method???
public class Scheduler {
 
	public static void main(String[] args) throws InterruptedException {
		printNumber();	
	}
	private static void printNumber()throws InterruptedException{
		int i = 0;
		Thread.sleep(3000);
		while(true){
		System.out.println(i++);
		}
	} 
}

Open in new window

0
 
TrigunaCommented:
To come out of a loop, you can use break after the Thread.sleep(3000).
To come out of a method, you can use return after the Thread.sleep(3000).
To come out of an application, you can use System.exit(0) after the Thread.sleep(3000).

But according to the code snippet, you can use a Timer and schedule the task for 3000 msecs and once it completes, you can return back and kill the timer. Doesnt it make sense?
0
 
TrigunaCommented:
Timer t = new Timer();
t.schedule(PrintNumber, 3000, 0);
In printnumber, after particular operation is over, you can say t.cancel();
0
 
bernerackermanAuthor Commented:
I don't understand how we can use scheduler. I got syntax errors. If you can give me the runnable code, I would appreciate it. muktajindal's method is good, but I don't want to use multi-thread :(
import java.util.Timer;
public class Try {
	public static void main(String[] args) {
		Timer t = new Timer();
		t.schedule(printNumber(), 3000, 0);  //syntax errors
	}
 
	private static void printNumber()throws InterruptedException{
	   System.out.println(i++);
	}
}

Open in new window

0
 
TrigunaCommented:
Method:
void java.util.Timer.schedule(TimerTask task, long delay, long period)
Parameters:
task - task to be scheduled.
delay - delay in milliseconds before task is to be executed.
period - time in milliseconds between successive task executions.

Create a class which extends TimerTask and implement the run method. Inside run method, you can print your numbers.

class PrintNumberTask extends TimerTask {
@Override
public void run() {
    // Print Number here.
}
}

And in the main method, you can just instantiate it like this.
Timer t = new Timer();
t.schedule(new PrintNumberTask(), 3000, 0);

Hope this helps.
0
 
bernerackermanAuthor Commented:
lots of syntax errors :(
Can you really give me a code, please?
import java.util.Timer;
class Try extends TimerTask {
	@Override
	public void run() {
	    int i = 0;
		System.out.println(i++); 
	}
	 public static void main(String[] args) {
	Timer t = new Timer();
	t.schedule(new Try(), 3000, 0);
	}
}

Open in new window

0
 
TrigunaCommented:

import java.util.Timer;
import java.util.TimerTask;

public class PrintNumber
{
public static Timer timer = new Timer();
public static int i = 0;

public static void main(String[] args)
{
timer.schedule(new PrintNumberTask(), 0, 3000);
}
}

class PrintNumberTask extends TimerTask
{

@Override
public void run()
{
System.out.println(PrintNumber.i++);
if (PrintNumber.i >= 3)
{
PrintNumber.timer.cancel();
}
}
}
0
 
TrigunaCommented:
Output of the above program is 0,1,2 and then it terminates.
0
 
bernerackermanAuthor Commented:
Hello Triguna,

First of all, thank you for your code. However, the code is not doing what I want to do. I got your exact output (0, 1, 2). My question is looking for a way to execute a function for running a certain period of time than stop. I thought if I can use your suggestion; scheduler to schedule the task for running 3 seconds than stop and continue whatever the rest of the code, then I can avoid the multi threading.
Lets make my question a bit clear.
1. when the main program execute the scheduler, the task should start right away without any delay.
2. the printNumber() should start running for 3 seconds,
3. the value of the number should be very big e.g. 4343473 by the time to stop the printNumber()
Hope I make my question a bit clear :)
0
 
TrigunaCommented:
I slightly modified the code.
Is this what you are looking at?

import java.util.Timer;
import java.util.TimerTask;
 
public class PrintNumber
{
   public static Timer timer = new Timer();
   public static int i = 0;
 
   public static void main(String[] args) throws InterruptedException
   {
      int t = 0;
      for (; t < 10; t++)
      {
         // Running 10 tasks.
         System.out.println("Running task " + t);
      }
      Thread.sleep(3000);
      timer.schedule(new PrintNumberTask(), 0, 3000);
      Thread.sleep(3000);
      Thread.sleep(3000);
      for (; t < 100; t++)
      {
         // Running next 100 tasks
         System.out.println("Running task " + t);
      }
   }
}
 
class PrintNumberTask extends TimerTask
{
 
   @Override
   public void run()
   {
      System.out.println(PrintNumber.i++);
      if (PrintNumber.i >= 3)
      {
         PrintNumber.timer.cancel();
      }
   }
}

Open in new window

0
 
TrigunaCommented:
Since I am running 3 tasks for 3 seconds, there was a sleep for 3 seconds 3 times. You can have only 1 thread.sleep.
0
 
bernerackermanAuthor Commented:
Your code still cannot address my question :(
1. when the main program execute the scheduler, the task should start right away without any delay.
2. the printNumber() should start running for only 3 seconds, After  3 seconds, the printNumber() stops doing anything.
3. the value of the number should be very big e.g. 4343473 by the time to stop the printNumber()
4. I just need to schedule one task i.e. to print the number.
5. please try to understand my question.  I would appreciate your effort for helping me :)
The code below is not I want. It delays 3 seconds and print i, and continue doing the same thing. I need printing the value of i for 3 second then stop.
import java.util.Timer;
import java.util.TimerTask;
 
public class PrintNumber
{
   public static Timer timer = new Timer();
   public static int i = 0;
 
   public static void main(String[] args) throws InterruptedException
   {
      timer.schedule(new PrintNumberTask(), 0, 3000);
   }
}
 
class PrintNumberTask extends TimerTask
{
 
   @Override
   public void run()
   {
      System.out.println(PrintNumber.i++);
   }
}

Open in new window

0
 
bernerackermanAuthor Commented:
Thank you very much :)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.