How to fix major lag in NSTimers? - objective-c

In a fairly simple application that I am making, I use many NSTimers, one which runs at a rate of .01 seconds that I use to change the position of multiple images. This causes major lag. How can I fix this? Please explain in detail, as I am fairly new to app dev.

From the NSTimer Docs (emphasis: mine):
A timer is not a real-time mechanism; it fires only when one of the
run loop modes to which the timer has been added is running and able
to check if the timer’s firing time has passed. Because of the various
input sources a typical run loop manages, the effective resolution of
the time interval for a timer is limited to on the order of 50-100
milliseconds. If a timer’s firing time occurs during a long callout or
while the run loop is in a mode that is not monitoring the timer, the
timer does not fire until the next time the run loop checks the timer.
Therefore, the actual time at which the timer fires potentially can be
a significant period of time after the scheduled firing time.
If you want to work at the display frequency, see CADisplayLink.
However, you should first understand where you program spends its time now to understand what makes it slow (profiler).

Related

How to stop simulation run after specific time NOT tick

all.
Regardless of what my model does, I want to stop the simulation after running for a specific time (real clock time). For example, stop after 5 or 10 or 15 minutes. I tried stopping it after 5 minutes using the RunEnvironment.getInstance()endAt(double tick) as follows:
RunEnvironment.getInstance()endAt(5000)
It stops at 4 minutes, 44 seconds. I came across this answer, but it seems not what I am looking for (I may be wrong). Is there a better way to achieve this? I am very new to RePast and somehow confused about the tick concept.
Thank you.
Here's a quote from a recent paper re. the tick concept that might help.
Events in Repast simulations are driven by a discrete-event scheduler. These events themselves are scheduled to occur at a particular tick. Ticks do not necessarily represent clock-time but rather the priority of its associated event. Ticks determine the order in which events occur with respect to each other. For example, if event A is scheduled at tick 3 and event B at tick 6, event A will occur before event B. Assuming nothing is scheduled at the intervening ticks, A will be immediately followed by B. There is no inherent notion of B occurring after a duration of 3 ticks. Of course, ticks can and are often given some temporal significance through the model implementation. A traffic simulation, for example, may move the traffic forward the equivalent of 30 seconds for each tick.
If you want to schedule a stop after some amount of walltime (e.g., 5 minutes) has elapsed, you could schedule an action that gets the time at its first invocation and then subsequently checks if the correct amount of time has elapsed. At that point, you could call RunEnvironment.getInstance().endRun(). How to do the time arithmetic is a Java question, so if you google for "Java time elapsed" or something like that you should get an answer.
As far as scheduling the action, you need to create a class that implements IAction (https://repast.github.io/docs/api/repast_simphony/repast/simphony/engine/schedule/IAction.html) and schedule that at whatever interval seems appropriate.

How to choose proper watchdog timer value

The question is:
How should I configure the Watchdog Timer if I have 3 tasks with different priorities and different execution time?
Say:
Task1: Highest Priority , Exec. Time = 5 ms
Task2: Medium Priority , Exec. Time = 10 ms
Task3: Lowest Priority , Exec. Time = 15 ms
The proper way to do this is
Create a special watchdog task that waits on 3 semaphores/mutexes/message queues (sequentially) in a loop
Feed those three semaphores from your worker tasks (each task feeds one semaphore of the watchdog task)
re-set the watchdog timer in the watchdog task's loop to the sum of the loop timing of all worker tasks (worst case) plus some headroom.
If any of your worker tasks or the watchdog tasks hangs, it will eventually block the watchdog task and the watchdog will expire. You want to make sure the watchdog is only re-triggered when all tasks are running properly. Use the simplest inter-task communication means your RTOS provides to make it as robust as possible against crashes.
Look at this definition
A watchdog timer is an electronic timer that is used to detect and recover from computer malfunctions. During normal operation, the computer regularly resets the watchdog timer to prevent it from elapsing, or "timing out"
So you set the watchdog timer value, that trigger watchdog when you are sure none of 3 tasks is running. To be more accurate, you reset the timer when you are sure all of the tasks are running. When a single task stopped due to unknown reason, you want to trigger watchdog (you can read more on it)
Now the real thing, what should be time for watchdog timer? you need to set a timer when you want to restart the program, so include all wait time for a task, delays in tasks and check worst-case time (max time) for all tasks to be executed at least once. then set the timer value a little bit more than this max value.

Does using Timers have negative effects on applications?

I am wondering about the Timer component and what, if any, negative effects occur because of its use or multiple instances of its use. In practice, should there be a limit as to how many timers one should use in a project at one time?
Well, everything is relative but a System.Windows.Forms.Timer is a pretty expensive object. It works by creating a hidden window, required to make the underlying winapi SetTimer() function work. This window is not shared, every timer object gets its own window. A window is in general one of the more expensive operating system objects.
So a very hard upper limit is that you can never have more than 10,000 enabled timers. Windows refuses to allow an app to create that many windows. You should stay considerably south of that limitation, given that all of the windows of all of the processes that run in one desktop session need to share a common heap. Or in other words, creating a lot of windows but staying below the 10,000 quota can negatively impact other processes, it can make them fail when the heap is exhausted.
I'd say a reasonable upper limit hovers around 100. That's a large number of moving parts to keep track of in general, assuming that all of these timers have different Tick event handlers. If they don't then you should tackle this a different way, you only ever need one Timer to measure an arbitrary number of intervals. Roughly the same way you keep appointments with single watch on your wrist. You do so by storing the due times in a SortedList and start the timer only for the first one that's due. When it ticks, work off the entries in the list that have the expired due time and repeat. When you add or remove a due time, stop the timer and restart it when there's a new first due time.
I am assuming you mean the winforms timer object So,
From the Docs:
A Timer is used to raise an event at user-defined intervals. This
Windows timer is designed for a single-threaded environment where UI
threads are used to perform processing. It requires that the user code
have a UI message pump available and always operate from the same
thread, or marshal the call onto another thread.
When you use this
timer, use the Tick event to perform a polling operation or to display
a splash screen for a specified period of time. Whenever the Enabled
property is set to true and the Interval property is greater than
zero, the Tick event is raised at intervals based on the Interval
property setting.
So reading that line by line if you start to pack your application with timers, you are quickly going to be racing the interval events for UI render time.
For instance: You have a clock application that uses a timer to run the clock. At each 1 second interval you have the application render the hands.
In this application you also let the user define as many 'alarms' as they want. Each one creating a new timer that will trigger at set times. These alarms are also allowed to be cyclical. That is to say you allow the user to set an 'alarm' that goes off every x seconds.
Now suppose the user has a long running task (access DB, network resource, calculate PI to 1500 chars etc) that happens on a cyclical alarm. Now suppose the user has 10 long running tasks that need to happen in order and need to happen at 3 4 and 5 second intervals.
The behavior of these timers would not be adequate for this application because the following would happen:
The clock would stop rendering during the execution of the 'alarms'
The alarms may run over one another and thus they would queue up but not happen when they were supposed to happen, because the UI thread is processing all messages synchronously.
you end up with an unresponsive UI that does not do what you want.
So to answer as best I can your actual question; there does not necessarily need to be a limit to the amount of timers, just the interval between when they will fire in conjunction with the consideration of the time it will take to process your event handler.
If you are using the timers to fire separate processing threads that are going to come back to the UI thread eventually and make changes, then no there does not feasibly need to be a limit until you run into the upper end of the performance of your target machine. That is to say at some point the amount of timers could be so large that you are calling more timer events and clogging the message queue to the point that the form rendering becomes affected.
So in short:
Negative effects:
Timers run in the UI thread so they are blocking
they can have unexpected behaviors if your interval is shorter than the amount of time it takes to process your event handler.
In practice the only time you should need to limit your usage of timers, like any component that the user does not control, is if they begin to affect the user experience.
I hope that reads a lot less 'ramble-y' than it felt when I was writing it.

Can a WinRT background task be long-lived if within CPU and Network limits?

Microsoft's documentation states:
Background tasks are meant to be short-lived tasks that do not consume a lot of resources.
It also says:
Each app on the lock screen receives 2 seconds of CPU time every 15 minutes, which can be used by all of the background tasks of the app. At the end of 15 minutes, each app on the lock screen receives another 2 seconds of CPU time for use by its background tasks.
I need to run a background task every two minutes to update my live-tile.
My app is a lock-screen-app.
Computation is within the CPU and network usage constraints
Can I create a permanent background task (e.g. something which polls a web service and pulls information, waits and loops) to create a OneShot TimeTrigger every two minutes or is there a better way of doing this?
My concern with the background task option is whether the runtime would deem the task inactive while it was sleeping and close it or something else like there's a limit on the number of times a live tile can be updated within 15 minutes...
Yes, if by long lived you mean under 25 minutes.
Time triggers cannot execute more frequent than 15 minutes. Creating a OneShot trigger that executes in 2 minutes is, that's an interesting idea and should work. Yes, background tasks can register other background tasks to keep this chain going. Should the user's machine be off when it execs it will queue later.
Having said that, updating your tile that frequently & using a background task is not a wise solution. Because, it is unreliable. Background tasks can be disabled, for one. But every 15 minutes, you are going to exceed your quota. Try using a Scheduled tile instead.

system.threading.timer

I need to have a specific process(method) run once a day at a given time and was wondering if this can be done using the timer control.
As has been stated, if your process isn't already running, then use Task Scheduler to handle this for you.
However, if you have some background service or something already running, then use a timer, and have it check the system time. Timers are not necessarily accurate, and after a day's worth of running, I would expect them to be way off.
Set up a timer with an interval of 3000ms or so, and when that interval hits, then check the system time to see if it is time for your method to run.
You should create a program that does that process, then exits.
You should then schedule the program using Windows Task Scheduler.