Matlab timer is not executed asynchronously [duplicate] - multithreading

I am trying to print a warning or just a message after every second, like "1 second elapsed".
Is there a possibility to realize that?
I tried it with tic toc and a loop, but it is pretty insufficient. Furthermore I never get exactly one second. Is there a command that prints every X ms automatically?
Any ideas?
Thanks in advance.

Use a timer object.
t = timer;
t.ExecutionMode = 'fixedRate';
t.Period = 1;
t.TimerFcn = #(~,~)disp('1s elapsed');
start(t)

As #Daniel suggested, timer objects are the way to go.
One thing to remember is that MATLAB timers execute asynchronously but are not truly parallel (even though timer objects run in a different thread, the MATLAB interpreter is still single-threaded).
So timer events might not fire (BusyMode property defaults to drop) it they occur during certain lengthy non-interruptible operations (like builtin functions, MEX-functions, etc..).
Here is an example:
>> t = timer('ExecutionMode','fixedRate', 'Period',1, 'BusyMode','drop', ...
'TimerFcn',#(~,~)disp(datestr(now,'MM:SS')));
>> start(t)
35:21
35:22
35:23
>> eig(rand(2000)); % <-- takes a couple of seconds to finish
35:27
35:28
35:29
35:30
>> stop(t)
Note how the timer event did not get a chance to execute while the EIG function was running.
Now if we change the BusyMode property to queue, then once again the event will not fire during the execution of EIG operation, but will immediately spit out all the queued events once EIG finishes:
>> t.BusyMode = 'queue';
>> start(t)
37:39
37:40
>> eig(rand(2000));
37:45
37:45
37:45
37:45
37:45
37:46
37:47
>> stop(t)
>> delete(t)

It is called pause. The optional argument specifies the duration in seconds. Documentation: http://www.mathworks.de/de/help/matlab/ref/pause.html

Related

Spawn Expect from a perl thread

I am working on a script which needs to spawn an Expect process periodically (every 5 mins) to do some work. Below is the code that I have that spawns an Expect process and does some work. The main process of the script is doing some other work at all times, for example it may wait for user input, because of that I am calling this function 'spawn_expect' in a thread that keeps calling it every 5 minutes, but the issue is that the Expect is not working as expected.
If however I replace the thread with another process, that is if I fork and let one process take care of spawning Expect and the other process does the main work of the script (for example waiting at a prompt) then Expect works fine.
My question is that is it possible to have a thread spawn Expect process ? do I have to resort to using a process to do this work ? Thanks !
sub spawn_expect {
my $expect = Expect->spawn($release_config{kinit_exec});
my $position = $expect->expect(10,
[qr/Password.*: /, sub {my $fh = shift; print $fh "password\n";}],
[timeout => sub {print "Timed out";}]);
# if this function is run via a process, $position is defined, if it is run via a thread, it is not defined
...
}
Create the Expect object beforehand (not inside a thread) and pass it to a thread
my $exp = Expect->spawn( ... );
$exp->raw_pty(1);
$exp->log_stdout(0);
my ($thr) = threads->create(\&login, $exp);
my #res = $thr->join();
# ...
sub login {
my $exp = shift;
my $position = $exp->expect( ... );
# ...
}
I tested with multiple threads, where one uses Expect with a custom test script and returns the script's output to the main thread. Let me know if I should post these (short) programs.
When the Expect object is created inside a thread it fails for me, too. My guess is that in that case it can't set up its pty the way it does that normally.
Given the clarification in a comment I'd use fork for the job though.

RobotC: Multithreading in TeleOp (controlling mode)

I am making a program for a robot in a competition, and need to multithread.
When I make a second task (task two()) and try to start (startTask) it with a button press from a controller, it just executes the first statement of the task and only as long as the button is pressed, instead of the whole block. I've tried many things including putting a loop in the second task also, using a function instead of a task and sleeping for 200 milliseconds before, and after the startTask(two); function, but the same thing happens every time.
I can't post my program because I don't want other people to steal it, sorry.
What edits will make it run the whole block?
Any help would be appreciated.
Since this is Controller Mode, I'm assuming that you are setting the motors to stop when the corresponding button is not pressed.
if([...])
[...]
else
{
setMotorSpeed(motor10, 0);
}
This is the cause for the stopping of the motors when you release. All of the other methods that you tried had nothing to do with this, so they shouldn't have worked.
You need to put something like this:
int Motor10Speed;
[...]
if([...])
[...]
else
{
setMotorSpeed(motor10, Motor10Speed);
}
This will control an individual motor. Repeat this for all other motors being used.
After that is done, make the function look something like this:
task mini_function();
task main()
{
[...]
}
task mini_function()
{
Motor10Speed = 50;
sleep(1000);
Motor10Speed = 0;
}
Expand the above program so it matches your current function, while using the MotorSpeed variables as setMotorSpeed variables.
This should make you able to drive and run a function at the same time without them interrupting each other.

how to make a tracking timer in command line with node.js

I am trying to build a simple time tracking tool in the command line and and basically i want to run start and stop commands and output the time elapsed. At the moment I am having problems because my timer variable is not holding values between requests. This is the simple script I have wrote until now;
Do I need to spawn another process or should I just store the start time in a .txt file or database and use it from there?
#! /usr/bin/env node
var cli = require('commander'),
time,
timer = null;
cli
.version('0.0.1');
cli
.command('start')
.description('Start timer')
.action(start);
cli
.command('stop')
.description('Stop timer')
.action(stop);
cli.parse(process.argv);
function start() {
timer = new Date;
}
function stop() {
time = new Date - timer;
hours = Math.floor(time/3600);
seconds = time % 3600;
minutes = Math.floor(seconds / 60);
seconds = seconds % 60;
seconds = Math.floor(seconds);
console.log(hours + ' hours ' + minutes + ' minutes ' + seconds + " seconds")
}
Without some external mechanism for storing state of ay kind (such as a database, flat file, etc) each invocation of your program will have no knowledge of what happened in any other invocation of it.
Each time you run the application all the variables are initialized, written to, read from, etc and then once your application stops everything is then binned, any memory it has used is returned to the operating system and all your variables disappear.
The simplest way to persist time would probably to have your code read and write to a flat file (maybe in a json format). This does have potential issues such as concurrency and file locking but I wouldn't worry about this till they actually become a problem. (and then you can just use a database etc).

How does the .Exist timeout work within QTP?

I've worked with the .Exist method quite a bit, but I recently moved to a new project (now using a WPF application) with QTP 11 (whereas previously I had QTP 10).
Now I'd like to check that a message does not exist by using object.Exist(2). Weirdly, I only get a result after ~23 seconds, instead of the 2 seconds I was expecting.
How does the timeout work? In previous projects, using object.Exist(2) would wait 2 seconds before determining that the object didn't exist. The QTP help file also says it should only wait for 2 seconds (the specified timeout parameter).
Now, it seems as though it's waiting for the Timeout Parameter (2 seconds) AND Object Synchronization Timeout (20 seconds).
Also, Smart Identification is disabled, so it shouldn't be waiting for that. Highlighting the object using the Object Repository instantly says the object doesn't exist.
Has the timeout behavior changed between QTP v10 and v11?
Why does it take so long to say an object doesn't exist?
The Exist method does not work for the last object only.
It works hierarchically - which means this method checks each parent object before checking the last one.
The timeout only works for the last object.
if you want to receive the answer immediately, I suggest you use the following code-
if WPFWindow("x").Exist(0) Then
if WPFWindow("x").WPFButton("y").Exist(0) Then
'action
End if
End if
Make sure you don't have "Smart Identification" enabled for the test object in the Object Repository. That can get in the way.
The additional time that you're encountering is the default timeout setting, which is set to 20 seconds by default. Any Wait or Exist timers will stack on top of the default timeout.
It can be changed in the test settings:
Test Settings > Run > Object synchronization timeout - set in seconds
or in the vbscript:
Setting("DefaultTimeout") = 4000 'set in milliseconds
Using DefaultTimeout function at the beginning of the driver script would be sufficient .
Setting("DefaultTimeout") = 10000 'set in milliseconds
If any object exceeds the timeout limit of 10 seconds as mentioned above then the object will fail to get captured and Run Results will show a failure
I would recommend going by with just the default timeout. Using .Exist(x) will use the mentioned time for each child.

Timer Job Scheduling on DataSheet Entry in SharePoint

I have a list on which I have an ItemUpdated handler.
When I edit using the datasheet view and modify every item, the ItemUpdated event will obviously run for every single item.
In my ItemUpdated event, I want it to check if there is a Timer Job scheduled to run. If there is, then extend the SPOneTimeSchedule schedule of this job to delay it by 5 seconds. If there isn't, then create the Timer Job and schedule it for 5 seconds from now.
I've tried looking to see if the job definition exists in the handler and if it does exist, then extend the schedule by 5 seconds. If it doesn't exist, then create the job definition to run in a minutes time.
MyTimerJob rollupJob = null;
foreach (SPJobDefinition job in web.Site.WebApplication.JobDefinitions)
{
if (job.Name == Constants.JOB_ROLLUP_NAME)
{
rollupJob = (MyTimerJob)job;
}
}
if (rollupJob == null)
{
rollupJob = new MyTimerJob(Constants.JOB_ROLLUP_NAME, web.Site.WebApplication);
}
SPOneTimeSchedule schedule = new SPOneTimeSchedule(DateTime.Now.AddSeconds(5));
rollupJob.Schedule = schedule;
rollupJob.Update();
When I try this out on the server, I get a lot of errors
"An update conflict has occurred, and you must re-try this action. The object MyTimerJob Name=MyTimerJobName Parent=SPWebApplication Name=SharePoint -80 is being updated by NT AUTHORITY\NETWORK SERVICE in the w3wp process
I think the job is probably running for the first time and once running, the other ItemUpdated events are coming in and finding the existing Job definition. It then tries to Update this definition even though it is currently being used. Should I make a new Job Definition name so that it doesn't step on top of the first? Or raise the time to a minute?
I solved this myself by just setting the delay to a minutes time from now regardless of whether a definition is found. This way, while it is busy, it will keep pushing back the scheduling of the job until it is done processing
This is because the event is asynchronous. You'll need to rethink exactly what you're trying to solve with this code and potentially re-factor it.
Maybe you should try using "lock" on the timer job object?

Resources