AS3 Delay Timer Execute and Start Timer - android

Hello I have a ActionScript 3.0 project and I have a timer that is running on 1000 millisecond intervals. I would like to delay this timer for 1500 milliseconds perform an action and start the timer again after the delay. I thought I could do this easily, but I'm having trouble, would it be better to stop the timer and perform the action and then listen for the action to be completed to start the timer again?
If you have time, I would appreciate the help.
Thank you,
Scientific

Assuming I understood your question, why not something like this? (UNTESTED CODE)
yourTimer.addEventListener(TimerEvent.TIMER, itIsTime);
function itIsTime(evt:TimerEvent):void {
yourTimer.stop();
yourTimer.reset();
if(yourTimer.delay == 1500){
//Do your stuff
...
yourTimer.delay = 1000;
yourTimer.start();
} else {
//Do your stuff
...
yourTimer.delay = 1500;
yourTimer.start();
}
}
Alternatively you could use 2 timers, but the idea is the same, after 1000 do one thing, after 1500 do something different, controlling when each timer goes off with the other timer's listener function.

Related

How do I work with the system clock / time in xamarin forms?

for a school project i'm making an app. The app is supposed to keep track of the time that you spend working on something specific. For example when i'm going to start my work shift, I would press a (start)button so the timer starts off and counts how much I've worked until i press a stop button.
I've got the xaml ready with all the buttons and labels.
My main problem is the timer. I would like to have a stopwatch underneath my start button, that shows the elapsed time. I've been looking for many many hours on github, stackoverflow, google and youtube and haven't found a solution.
If it isn't easy/possible to implement a stopwatch, i would at least need the app to check for the system time when the start and stop buttons are clicked, to calculate the difference in time.
So far I haven't been able to get any of those functions working.
Thanks in advance! - MagSky
.NET has a built in Stopwatch class you can use
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
// do some work here
stopWatch.Stop();
// Get the elapsed time as a TimeSpan value.
TimeSpan ts = stopWatch.Elapsed;
to display a Timer in the UI, use System.Timers.Timer instead
int secs = 0;
// fire an event every 1000 ms
Timer timer = new Timer(1000);
// when event fires, update Label
timer.Elapsed += (sender, e) => { secs++; myLabel.Text = $"{secs} seconds"; };
// start the timer
timer.Start();

While loop for a limited time (android)

how do I implement a while loop for example ten seconds in eclipse? can someone help me? Have I to use a timer?
Timer timer = new Timer();
timer.schedule( new performClass(), 30000 );
Thank you.
You shouldn't, in any language on any platform. Busy waiting is a waste of processor cycles and battery power, and can keep background tasks from getting the processor. The correct solution is to use a timer, or to spawn off a thread that sleeps for the required amount of time.
You want your while to execute x times during 10 seconds?
long startTime = System.currentTimeMillis();
while( startTime + 10000 > System.currentTimeMillis())
{
}
If you objective is to pause execution for ten seconds you can try http://docs.oracle.com/javase/tutorial/essential/concurrency/sleep.html

Android: Chronometer SetBase in minutes

Is there a way by which using the android chronometer class to set base of the chronometer in 15 minutes and from that period the times goes down until 0 seconds?
I have tried with setBase(60000) but this isn't work.
Check out this thread Android: chronometer as a persistent stopwatch. How to set starting time? What is Chronometer "Base"? as well as this thread Android - Get time of chronometer widget. Neither answers your question directly, but the nuggets there should lead you to an answer.
In general the chronometer works like this (if you would like to set the Base to a specific nr):
mChronometer.setBase(SystemClock.elapsedRealtime() - (nr_of_min * 60000 + nr_of_sec * 1000)))
what you are asking can be done through a countdown (http://developer.android.com/reference/android/os/CountDownTimer.html)
Or create your own countdown by using the chronometer like this (more work should be done cause i just wrote this and did not test it yet)
private OnChronometerTickListener countUp = new OnChronometerTickListener(){
#Override
public void onChronometerTick(Chronometer chronometer){
long elapsedTime = (SystemClock.elapsedRealtime() - mChronometerCountUp.getBase()) / 60000;
Log.v("counting up", elapsedTime);
// you will see the time counting up
count_down--;
if(count_down == 0){
mChronometerCountUp.stop();
}
// an int which will count down,
// this is not (very) accurate due to the fact that u r using the update part of the chronometer
// u just might implement the countdown i guess
// or 2 chronometers (one counting up and an other counting down using the elapsed time :p)
// just remember programming is creating ur solution to problems u face its like expression urself
};
};
http://developer.android.com/reference/android/widget/Chronometer.html
For set the base time you can use elapsedRealtime(), and you can output format with setFormat()

Precision of delay

I have a problem with this code used for Android (Java)
handler.postDelayed(new Runnable(){
public void run(){
// Your code goes here...
}
}, 500);
If the delay is about 500ms then the program seems to repeat the task at 0.5s, but if I change to less than 100ms or even less it does not follow any more. I test the brightness change and for a while it can repeat the change of brightness at that rate, but then slow down and come back to normal flash rate again. It seems unstable. Do you have any code that give exact delay regardless of the load of the phone's CPU.
Many thanks
Not from Java, no; stock Java isn't a real-time system.
Timing precision is subject to the whims of the JVM and the OS's scheduler. You may be able to get incrementally more precise, but there's no guarantee of the kind of precision you're looking for.
You might be able to do something more precise if you use a CountDownTimer which has a periodic tick. Essentially you set it to count down for a period which can be hours if need be, and there are two methods one method is called on each tick, and the other at the end of the timer at which point you could start another one. Anyway you could set the tick to be very fast, and then only kick off the code at the delay point by check the actual time difference in the click. I think thats about the best you could do. Essentially inside the tick you would issue a signal if the right amout of time had actually passed. That signal would either kick off the thread or release something the already running thread was waiting on. What is the value of the CountDownTimer, I guess its just that you can do a very frequent polling, and elapsed time check. Although its not guaranteed, the time between the ticks you can set it to a high frequency and check/poll very frequently. This could lead to a smooth performance not unlike a realtime system. Its more likely to be accurate because its just issuing a signal and not taking up the resources of threading just to issue the signal. You might also try an IntentService to perform the tasks and just call startService(intentToIntentService) each call. See if the threading works better inside a service like IntentService which does queue them up I believe.
Date startDate = new Date();
long startTime = startDate.getTime();
// Tick called every 10th of a second. OnFinish called at Signal.
CountDownTimer ctDownTimer = new CountDownTimer(30000, 100) {
long startIntervalTime=startTime;
public void onTick(long millisUntilFinished) {
Date now = new Date();
long nowTime = now.getTime();
if ((startIntervalTime - nowTime) > 100)
{
issueSignal();
intervalStartTime=nowTime;
}
now=null;
}
public void onFinish() {
Log.d("MyClass", "Done") // Maybe start out.
}
}.start();

Problem synchronizing sound and display

I have an app that plays an mp3 file and I'm trying to update a custom field in synchrony with certain times we have tabulated for the sound playback (kind of like a karaoke effect). I'm using a Handler to schedule these updates. In my custom field class, I define a Runnable that is supposed to run the update at the right time:
private final Runnable mTrigger = new Runnable() {
#Override
public void run() {
int now = mPlayer.getCurrentPosition();
if (mState == STATE_PLAYING && mUpdateAction != null) {
if (mTriggerTime - now > MAX_PREMATURE_TRIGGER) {
// Sound is lagging too much; reschedule this trigger
mHandler.postDelayed(this, mTriggerTime - now);
} else {
// Run the update
mUpdateAction.run();
}
}
}
};
When I call mPlayer.start() I schedule the first update by calling mHandler.postDelayed(mTrigger, timeToFirstUpdate). Each update action decides what the next update will be and schedules it (by calling mHandler.postDelayed(mTrigger, timeToNextUpdate)). The updates times are typically a few hundred milliseconds apart.
The problem is that, while some updates are happening promptly at the scheduled times, others can be delayed by 200 milliseconds or more, which is quite noticeable to the user. I'm not doing anything in my app between these updates other than playing the sound. (No background worker threads; no other display updates.) The delays appear to be random and vary considerably each time through.
I didn't think that the timing for postDelayed would be this imprecise! I don't know if this is an emulator issue or a problem with my approach. Does sound playback screw up the timing of the UI thread loop? Should I move the timing into a background thread (and is it safe to call mPlayer.getCurrentPosition() from a background thread)? Something else?
After much experimenting, it seems like the problem is the emulator. When I ran everything on a speedier workstation, the problem seems to have gone away.

Categories

Resources