[Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

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

Posted on 2008-11-04
18
Medium Priority
?
226 Views
Last Modified: 2013-11-23
//just make the example simple -
//the processing time is 3 seconds
...
while(true){
    counter++;
}
//after 3 seconds, continue to do the rest...
...
...
...
0
Comment
Question by:bernerackerman
  • 9
  • 6
  • 2
  • +1
18 Comments
 
LVL 5

Expert Comment

by:Triguna
ID: 22883151
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
 
LVL 3

Expert Comment

by:SreejithG
ID: 22883152
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
 
LVL 5

Expert Comment

by:Triguna
ID: 22883156
Or you can achieve this case using a Thread.
Just say Thread.sleep(3000). that is sleep for 3 seconds.
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 5

Expert Comment

by:muktajindal
ID: 22883358
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
 

Author Comment

by:bernerackerman
ID: 22883423
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
 
LVL 5

Expert Comment

by:Triguna
ID: 22883476
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
 
LVL 5

Expert Comment

by:Triguna
ID: 22883488
Timer t = new Timer();
t.schedule(PrintNumber, 3000, 0);
In printnumber, after particular operation is over, you can say t.cancel();
0
 
LVL 5

Accepted Solution

by:
muktajindal earned 1000 total points
ID: 22883502
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
 

Author Comment

by:bernerackerman
ID: 22891137
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
 
LVL 5

Expert Comment

by:Triguna
ID: 22892166
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
 

Author Comment

by:bernerackerman
ID: 22892307
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
 
LVL 5

Expert Comment

by:Triguna
ID: 22892368

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
 
LVL 5

Expert Comment

by:Triguna
ID: 22892370
Output of the above program is 0,1,2 and then it terminates.
0
 

Author Comment

by:bernerackerman
ID: 22892529
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
 
LVL 5

Expert Comment

by:Triguna
ID: 22892559
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
 
LVL 5

Expert Comment

by:Triguna
ID: 22892562
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
 

Author Comment

by:bernerackerman
ID: 22892661
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
 

Author Closing Comment

by:bernerackerman
ID: 31513409
Thank you very much :)
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
In this post we will learn different types of Android Layout and some basics of an Android App.
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
In a recent question (https://www.experts-exchange.com/questions/29004105/Run-AutoHotkey-script-directly-from-Notepad.html) here at Experts Exchange, a member asked how to run an AutoHotkey script (.AHK) directly from Notepad++ (aka NPP). This video…
Suggested Courses
Course of the Month20 days, 14 hours left to enroll

810 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question