wxTimerEvent does not always call at the expected interval - events

I am using wxTimerEvent() to call a function at a certain frequency. But it does not always call the function as expected.
For example, it works fine for a random time duration, and then it does not call the function at all for a few seconds. SHere is my block of code. Please help me figure out this issue...
class MyFrame : public wxFrame
{
public:
...
void OnTimer(wxTimerEvent& event);
private:
wxTimer *mTimer
wxDECLARE_EVENT_TABLE();
};
wxBEGIN_EVENT_TABLE(MyFrame, wxFrame)
EVT_TIMER(TIMER_ID, MyFrame::OnTimer)
wxEND_EVENT_TABLE()
MyFrame::MyFrame()
{
mTimer = new wxTimer(this, TIMER_ID)
m_timer.Start(100); // 100 millisecond interval
}
void MyFrame::OnTimer(wxTimerEvent& event)
{
// my logic -this is working fine... just set a flag.
}

Timers are not guaranteed to fire at exactly the specified interval, but for a 100ms timer to not be called for several seconds is not normal at all. I suspect your code doesn't return to the event loop, preventing it from dispatching the timer events. If you're sure this is not the case, you would really need to produce an example reproducing the problem (ideally the smallest possible change to the wxWidgets minimal sample) and open a bug report about it (please be sure to mention your wxWidgets version and platform if you do this).

Related

XTestFakeKeyEvent calls get swallowed

I'm trying to spoof keystrokes; to be a bit more precise: I'm replaying a number of keystrokes which should all get sent at a certain time - sometimes several at the same time (or at least as close together as reasonably possible).
Implementing this using XTestFakeKeyEvent, I've come across a problem. While what I've written so far mostly works as it is intended and sends the events at the correct time, sometimes a number of them will fail. XTestFakeKeyEvent never returns zero (which would indicate failure), but these events never seem to reach the application I'm trying to send them to. I suspect that this might be due to the frequency of calls being too high (sometimes 100+/second) as it looks like it's more prone to fail when there's a large number of keystrokes/second.
A little program to illustrate what I'm doing, incomplete and without error checks for the sake of conciseness:
// #includes ...
struct action {
int time; // Time where this should be executed.
int down; // Keydown or keyup?
int code; // The VK to simulate the event for.
};
Display *display;
int nactions; // actions array length.
struct action *actions; // Array of actions we'll want to "execute".
int main(void)
{
display = XOpenDisplay(NULL);
nactions = get_actions(&actions);
int cur_time;
int cur_i = 0;
struct action *cur_action;
// While there's still actions to execute.
while (cur_i < nactions) {
cur_time = get_time();
cur_action = actions + cur_i;
// For each action that is (over)due.
while ((cur_action = actions + cur_i)->time <= cur_time) {
cur_i++;
XTestFakeKeyEvent(display, cur_action->code,
cur_action->down, CurrentTime);
XFlush(display);
}
// Sleep for 1ms.
nanosleep((struct timespec[]){{0, 1000000L}}, NULL);
}
}
I realize that the code above is very specific to my case, but I suspect that this is a broader problem - which is also why I'm asking this here.
Is there a limit to how often you can/should flush XEvents? Could the application I'm sending this to be the issue, maybe failing to read them quickly enough?
It's been a little while but after some tinkering, it turned out that my delay between key down and key up was simply too low. After setting it to 15ms the application registered the actions as keystrokes properly and (still) with very high accuracy.
I feel a little silly in retrospect, but I do feel like this might be something others could stumble over as well.

Controlling animations in an animator via parameters, in sequences

So I am animating an avatar, and this avatar has its own animator with states and such.
When interacting with props, the props itself has an animator with states in it. In both case, I transition to some animations through parameters in the animator (bool type).
For example, for a door, the character will have "isOpeningDoor", while the door will have "isOpen".
Now the question: when I change the value on an animator on GO1, and then change the bool on GO2; do the first animation finish and then the second start? Because in my case, it does not happen; they start almost at the same time.
void OnTriggerEnter (collider door)
{
if (door.gameObject.tag=="door")
{
GOAnimator1.SetBool("isOpeningDoor", true);
GOAnimator2.SetBool("isOpen", true);
}
}
I believe that I am doing it wrong, since I change the parameter on the animator, but I do not check for the animation to end; is this even possible or am I doing something not kosher?
I really think it might be doable!
As you have it in your code now, the animations on GO1 and GO2 start at almost the same time because that's how it's written. The OnTriggerEnter() function will complete the execution in the frame it is called, and return the control to Unity.
What I think that might help you are coroutines and sendMessage between gameobjects:
http://docs.unity3d.com/Manual/Coroutines.html
http://docs.unity3d.com/ScriptReference/GameObject.SendMessage.html
The idea is to:
Create a coroutine in GO2 that waits an amount of time until it sets the GOAnimator2 variable to activate the door animation.
Create a function in GO2 that calls the aforementioned coroutine
From the OnTriggerEnter() send a message to GO2 to execute the newly created function
It reads complicated, but it's fairly simple. The execution would be like this:
1.Code for the coroutine:
function GO2coroutine(){
float timeToWait = 0.5f; //Tweak this
for ( float t = 0f; t < timeToWait; t+=time.deltaTime)
yield;
GetComponent<Animator>().SetBool("isOpen",true);
}
Code for the function calling it:
function callCoroutine() {
StartCoroutine("Fade");
}
And the code modification for your OnTriggerEnter():
void OnTriggerEnter (collider door)
{
if (door.gameObject.tag=="door")
{
GOAnimator1.SetBool("isOpeningDoor", true);
GO2.SendMessage("callCoroutine");
}
}
I didn't have a chance to test the code, so please don't copy paste it, there might be slight changes to do.
There is another way, but I don't like it much. That is making the animation longer with an idle status to wait for the first game object animation to end... but it will be a hassle in case you shorten the animation because you have to, or have any other models or events.
Anyway, I think the way to go is with the coroutine! Good Luck!

CFRunLoopSourceSignal doesn't work

I'm debugging Qt5.3.1 on Mac, because my program freezes sometimes (intermittent ). I discovered that it is because the QTimer can't work properly.
In Qt code, they use the following two lines to trigger function activateTimersSourceCallback
CFRunLoopSourceSignal(d->activateTimersSourceRef);
CFRunLoopWakeUp(mainRunLoop());
void QCocoaEventDispatcherPrivate::activateTimersSourceCallback(void *info)
{
static int counter = 0;
NSLog(#"finished activeteTimersSourceCallback %d", counter++);
}
but sometimes, these two lines doesn't work, activateTimersSourceCallback won't get called.
I googled, but I couldn't find any solution? is this a known OS bug?
the initialization details:
// keep our sources running when modal loops are running
CFRunLoopAddCommonMode(mainRunLoop(), (CFStringRef) NSModalPanelRunLoopMode);
CFRunLoopSourceContext context;
bzero(&context, sizeof(CFRunLoopSourceContext));
context.info = d;
context.equal = runLoopSourceEqualCallback;
// source used to activate timers
context.perform = QCocoaEventDispatcherPrivate::activateTimersSourceCallback;
d->activateTimersSourceRef = CFRunLoopSourceCreate(kCFAllocatorDefault, 0, &context);
Q_ASSERT(d->activateTimersSourceRef);
CFRunLoopAddSource(mainRunLoop(), d->activateTimersSourceRef, kCFRunLoopCommonModes);
Such behavior very likely can occur when UI event loop is overloaded with events or some business logic takes too long time. You should to check your business logic and move it to separate thread or run asynchronous.

How do you set periodic timers in d3.js?

I want to run a particular function every 5 minutes. If I write code like this:
function f() {
console.log("hi");
d3.timer(f, 5*60*1000);
return true;
}
d3.timer(f, 5*60*1000);
then f seems to run once and then never again.
I achieved the desired behavior by creating a clone of f called f2: f calls d3.timer(f2) and f2 call d3.timer(f). This seems like an ugly hack. Is there a better way?
I think #nrabinowitz's answer is probably the best and simplest, but if you'd really like to use d3.timer, here's how you'd do it.
var interval = 1000; // one second in milliseconds
var makeCallback = function() {
// note that we're returning a new callback function each time
return function() {
console.log('OH HAI!!');
d3.timer(makeCallback(), interval);
return true;
}
};
d3.timer(makeCallback(), interval);
Your code isn't working as expected because d3.js maps timers to function instances (see the code here: https://github.com/mbostock/d3/blob/master/d3.v2.js#L4073), so your code was doing the following:
set timer with callback f()
f() is called after five minutes
f() logs to the console, creates a new timer which also uses f() as its callback, and then cancels that timer by returning true.
The code in my answer solves the problem by returning a new function instance each time.
Of course, this is way more complicated and harder to understand that just using setInterval, so you should do that.
This sounds like a job for the standard JavaScript setInterval() method:
setInterval(f, 5*60*1000);
If you need it to run an animation at each invocation, that's where d3.timer would be useful - otherwise, the standard setInterval and setTimeout methods are likely to be easier.
Looks like d3.interval is a thing, and is meant to be a replacement for setInterval: https://github.com/d3/d3-timer#interval
var interval = d3.timeout(callback, interval_time, optional_delay);

Performing an action ONCE after a delay of n seconds, WP7 C#

I'm looking for a simple way to perform an action/method after a delay of n seconds. The thing I found a few examples but they seem overly complex for when on my last platform, iOS, it was just
[self performSelector:#selector(methodname) withDelay:3];
Any tips or code snippets would be much appreciated.
You can also use Scheduler.Dispatcher from Microsoft.Phone.Reactive:
Scheduler.Dispatcher.Schedule(MethodName, TimeSpan.FromSeconds(5));
private void MethodName()
{
// This happens 5 seconds later (on the UI thread)
}
DispatcherTimer DelayedTimer = new DispatcherTimer()
{
Interval = TimeSpan.FromSeconds(5)
};
DelayedTimer.Tick += (s, e) =>
{
//perform action
DelayedTimer.Stop();
}
DelayedTimer.Start();
For Windows Phone 8 you can use
await Task.Delay(milliseconds);
DispatcherTimer timer = new DispatcherTimer();
timer.Tick += (s, e) =>
{
// do some very quick work here
// update the UI
StatusText.Text = DateTime.Now.Second.ToString();
};
timer.Interval = TimeSpan.FromSeconds(1);
timer.Start();
Note that what you're doing here is interrupting the UI thread, not really running anything on a separate thread. It's not suitable for anything long-running and cpu-intensive, but rather something where you need to execute on a regular interval. Clock UI updates are a perfect example.
Also Timers are not guaranteed to execute exactly when the time interval occurs, but they are guaranteed to not execute before the time interval occurs. This is because DispatcherTimer operations are placed on the Dispatcher queue like other operations. When the DispatcherTimer operation executes is dependent on the other jobs in the queue and their priorities.
For more information use this link
If you want to use Timer for the background task then use the
System.Threading.Timer instead of DispatcherTimer
For more information use this link

Resources