Creating delay between measurements - java

I am trying to make a set of measurements of signal strength, so i want to make a delay between same method (that return needed value) execution - value1...delay....value2....delay.... Currently i am using
Thread.sleep(DELAY);
Such way of creating the delay seems to work, but as I understood it makes the whole app to stop. I have looked through Android Developers website and found some other ways using Timer and ScheduledExecutorService. But i do not fully understand how to create a delay using those 2 ways. May be someone will be some kind and give me some ideas or directions to start with?

You could use a Runnable and a handler.
private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
// Get the difference in ms
long millis = SystemClock.uptimeMillis() - mStartTime;
// Format to hours/minutes/seconds
mTimeInSec = (int) (millis / 1000);
// Do your thing
// Update at the next second
mHandler.postAtTime(this, mStartTime + ((mTimeInSec + 1) * 1000));
}
};
And start this with a handler:
mHandler.postDelayed(mUpdateTimeTask, 100);
Ofcourse you have to have a global mHandler (private Handler mHandler = new Handler();) and a starting time (also the uptimeMillis). This updates every second, but you can change it for a longer period of time.
http://developer.android.com/reference/android/os/Handler.html

java.util.concurrent.Executors.newScheduledThreadPool(1).scheduleAtFixedRate(new java.lang.Runnable()
{
#Override
public void run()
{
System.out.println("call the method that checks the signal strength here");
}
},
1,
1,
java.util.concurrent.TimeUnit.SECONDS
);
This is the snippet of code which will call some method after initial delay of 1 second every 1 second.

There is a tutorial about how to create a simple android Countdown timer. You can take a look, this may help.

To use Timer you create a Timer instance
Timer mTimer = new Timer();
Now the task you wish to run can be scheduled.
mTimer.scheduleAtFixedRate(new TimerTask() {
public void run() {
//THE TASK
}
}, DELAY, PERIOD);
DELAY = amount of time in milliseconds before first execution.
LONG = amount of time in milliseconds between subsequent executions.
See here for more.

The documentation page for ScheduledExecutorService gives a good example of how to use it:
import static java.util.concurrent.TimeUnit.*;
class BeeperControl {
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
public void beepForAnHour() {
final Runnable beeper = new Runnable() {
public void run() {
System.out.println("beep");
}
};
// Run the beeper Runnable every 10 seconds after a 10 second wait
final ScheduledFuture<?> beeperHandle = scheduler.scheduleAtFixedRate( beeper, 10, 10, SECONDS ) ;
// Schedule something to cancel the beeper after an hour
scheduler.schedule( new Runnable() {
public void run() {
beeperHandle.cancel(true);
}
}, 60 * 60, SECONDS);
}
}

Related

Java timer that limits the amount of time a method can run for

I am writing a web crawler and part of the specifications is that it will crawl the web for a user-specified amount of time. In order to do that I am trying to use the Timer and TimerTask methods. The code I have now is attempt number two. I have watched a few tutorials though none of them are quite what I need. I have also read through the documentation. I have been working on this project for a few weeks now and it is due tonight. I am not sure where to turn to next.
public void myTimer (String url, long time)
{
Timer webTimer = new Timer();
TimerTask timer;
timer = new TimerTask()
{
public void run()
{
long limit = calculateTimer(time);
while(System.currentTimeMillis() < limit)
{
webcrawler crawler1 = new webcrawler();
crawler1.Crawl(url);
}
System.out.println("times Up");
}
};
webTimer.schedule(timer, 1000);
}
I am guessing the .Crawl() is starting a loop and keeping that thread busy, which means it cannot check the while condition. I do not know your implementation of the crawler but i would recommend a function stopCrawling which would set a boolean to true to break the loop inside that class. Than I would do something like this:
public void startCrawler (String url, long time){
webcrawler crawler1 = new webcrawler();
crawler1.Crawl(url);
TimerTask task = new TimerTask() {
public void run() {
crawler1.stopCrawling()
}
};
Timer timer = new Timer("Timer");
timer.schedule(task, time);
}

How to schedule a periodic task but stop and return result if a condition is fulfilled (Java)

I need to execute a certain task periodically within a certain timeout.
But dependent on the result of the task, I want to stop before the end of the timeout is reached. And in addition I need a reference to the currently executed task in order to have the chance to ask for the result.
Solution to 1) is no problem, because it can be solved with the little code snipped shown below. But I can not figure out how to integrate 2). So with this code example, I would like that the beeper object runs code which can have a positive or a negative result and based on (for example) a positive result, the beeper task should no longer be executed periodically.
class BeeperControl {
private final ScheduledExecutorService scheduler =
Executors.newScheduledThreadPool(1);
public void beepForAnHour() {
final Runnable beeper = new Runnable() {
public void run() { System.out.println("beep"); }
};
final ScheduledFuture<?> beeperHandle =
scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS);
scheduler.schedule(new Runnable() {
public void run() { beeperHandle.cancel(true); }
}, 60 * 60, SECONDS);
}
}
In your run method if condition is fulfilled then invoke scheduler.shutdown(). That should do exactly what you want.
public void beepForAnHour() {
final Runnable beeper = new Runnable() {
public void run() {
System.out.println("beep");
if(isMyCondition() {
scheduler.shutdown();
}
}
};
See javadoc for ExecutorService.shutdown()

Perform a task each interval

So I'm trying to schedule a time instance where it repeats every 10 seconds. Right now I have something that does a task after 10 seconds, but how do I make it so that it resets after doing so.
this.schedule = TimerManager.getInstance().schedule(new Runnable() {
#Override
public void run() {
chrs.get(0).getMap().spawnMonsterOnGroudBelow(MapleLifeFactory.getMonster(100100), chrs.get(0).getPosition());
}
}, time);
}
time is equal to 10000 milliseconds, and thus 10 seconds.
1) Create ScheduledExecutorService
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
2) Create and schedule your Runnable:
Runnable task = new Runnable() {
#Override
public void run() {
System.out.println("Done:" + new Date(System.currentTimeMillis()));
// some long task can be here
executor.schedule(this, 10, TimeUnit.SECONDS);
}
};
//can be 0 if you want to run it fist time without 10 sec delay
executor.schedule(task, 10, TimeUnit.SECONDS);
If you don't care about runnable duration and always want to fire event every 10 secs
executor.scheduleAtFixedRate(new Runnable() {
#Override
public void run() {
System.out.println("Done:" + new Date(System.currentTimeMillis()));
}
}, /* same, can be 0*/ 10 , 10, TimeUnit.SECONDS);
3) Use this when you exit program
executor.shutdown();
Perhaps consider using a ScheduledExecutorService
See http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ScheduledExecutorService.html
You can use scheduleAtFixedRate method instead.
See this question Creating a repeating timer reminder in Java

Java: Scheduling a task in random intervals

I am quite new to Java and I'm trying to generate a task that will run every 5 to 10 seconds, so at any interval in the area between 5 to 10, including 10.
I tried several things but nothing is working so far. My latest effort is below:
timer= new Timer();
Random generator = new Random();
int interval;
//The task will run after 10 seconds for the first time:
timer.schedule(task, 10000);
//Wait for the first execution of the task to finish:
try {
sleep(10000);
} catch(InterruptedException ex) {
ex.printStackTrace();
}
//Afterwards, run it every 5 to 10 seconds, until a condition becomes true:
while(!some_condition)){
interval = (generator.nextInt(6)+5)*1000;
timer.schedule(task,interval);
try {
sleep(interval);
} catch(InterruptedException ex) {
ex.printStackTrace();
}
}
"task" is a TimerTask. What I get is:
Exception in thread "Thread-4" java.lang.IllegalStateException: Task already scheduled or cancelled
I understand from here that a TimerTask cannot be reused, but I am not sure how to fix it. By the way the my TimerTask is quite elaborate and lasts itself at least 1,5 seconds.
Any help will be really appreciated, thanks!
try
public class Test1 {
static Timer timer = new Timer();
static class Task extends TimerTask {
#Override
public void run() {
int delay = (5 + new Random().nextInt(5)) * 1000;
timer.schedule(new Task(), delay);
System.out.println(new Date());
}
}
public static void main(String[] args) throws Exception {
new Task().run();
}
}
Create a new Timer for each task instead, like you already do: timer= new Timer();
And if you want to synchronize your code with your threaded tasks, use semaphores and not sleep(10000). This might work if you're lucky, but it's definitely wrong because you cannot be sure your task has actually finished.

How to run a method at XX:XX:XX time?

HI
I want to run a method in my program evry X hours, how to do that ?
Im googling and there is nothing :/
You could consider Quartz.
It is some sort of cron that runs inside java. I admit though that it is probably an overkill if you want to schedule only one job.
You could take a look at the Timer class, but the best option is to use a ScheduledExecutorService:
e.g. This will beep at a scheduled rate:
import static java.util.concurrent.TimeUnit.*;
class BeeperControl {
private final ScheduledExecutorService scheduler =
Executors.newScheduledThreadPool(1);
public void beepForAnHour() {
final Runnable beeper = new Runnable() {
public void run() {
System.out.println("beep");
}
};
final ScheduledFuture<?> beeperHandle =
scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS);
scheduler.schedule(new Runnable() {
public void run() {
beeperHandle.cancel(true);
}
}, 60 * 60, SECONDS);
}
}
I use the Quartz framework for most of my scheduling ( http://www.quartz-scheduler.org/ ) but if you're doing something simple, java.util.Timer is fine.
// in a class body...
public static void main( String[] argv ) {
Timer timer = new Timer();
int secondsBetweenRuns = 3600;
timer.schedule( new MyOwnTask(), 0, secondsBetweenRuns * 1000 );
}
static class MyOwnTask extends TimerTask {
public void run() {
doWhateverYouNeedToDoEveryHour();
}
}
Scheduled Task (in Windows) or Cron (in Unix)
You could save the time at a certain point, than start a timer. When the time is up, you run the method and restart the timer.

Categories