Trials Timer with Read and Write - multithreading

I am creating a GUI in Matlab that will read and write data to a text file based on the trial duration. The user will enter the number of trials and trial duration and
then push the "start" button.
For example the user enters 5 trials at 10 seconds duration. While starting the 1st trial, I will need to read/write data continuously for 10 seconds, then stop and save the text file. This process will continue for the next 5 trials. Here is a brief code I tried to implement below.
How can I run both the timer for 10 seconds and simultaneously read/write data with that time limit?
Thanks in advance.
% Get Number of Trials
number_trials = str2double(get(handles.Number_Trials,'String'));
% Get Trial Duration
trial_duration = str2double(get(handles.Trial_Duration,'String'));
% Timer Counter
global timer_cnt
timer_cnt = 0;
global eye_data
eye_data = 0;
for i = 1:number_trials
% Set Current Trial Executing
set(handles.Current_Trial_Text,'String',num2str(i));
% Set Text File Specifications
data_fname = get(handles.Data_Filename_Edit_Text,'String');
file_fname = '.dat';
data_fname_txt = strcat(data_fname,file_fname);
% Timer Object
fprintf('%s\n','Timer Started');
% Pauses 10 Seconds
t = timer('TimerFcn','stat=false','StartDelay',10);
start(t);
stat = true;
while(stat == true)
disp('.');
pause(1)
end
fprintf('%s\n','Timer Ended');
delete(t);
end

In my experience, timers are usually used in the context of "wait this amount of time, then do foo" rather than how you're using it, which is "do foo until you've done it for this amount of time".
The humble tic/toc functions can do this for you.
t_start = tic;
while toc(t_start) < 10
% do data collection
end

Related

How to break out of loop when URL read is taking too long

Hi I have the following code to skip the particular URL if it is taking too long to read.
timeout = 30
loop begins below for different urlz {
timeout_start = time.time()
webpage = urlopen(urlz[i]).read()
if time.time() > timeout_start + timeout:
continue}
My question is; wont the program execute the line of code "webpage = urlopen(urlz[i]).read()" before moving down to check the if condition? In that case I think it wont detect if the page is taking too long (more than 30 seconds to read). I basically want to skip this URL and move on to the next one if the program is stuck for 30 seconds (i.e. we have run into a problem when reading this particular URL).
The urlopen() function has a timeout method inbuilt:
urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)
So in your code:
timeout = 30
loop begins below for different urlz {
try:
webpage = urlopen(urlz[i], timeout=timeout).read()
}

Timing issue in windows rather than linux

I have the following function from a colleague who was previously working for the company and the comments are self explanatory, the problem is I'm right now using windows, and there issues with the synchornization with the device.
Would someone address or know a solution in windows for sync with a device ?
def sync_time(self):
"""Sync time on SmartScan."""
# On a SmartScan time can be set only by the precision of seconds
# So we need to wait for the next full second until we can send
# the packet on it's way to the scanner.
# It's not perfect, but the error should be more or less constant.
message = Maint()
message.state = message.OP_NO_CHANGE
now = datetime.datetime.utcnow()
epoch = datetime.datetime(1970, 1, 1)
# int and datetime objects
seconds = int((now - epoch).total_seconds()) + 1 # + sync second
utctime = datetime.datetime.utcfromtimestamp(seconds)
# wait until next full second
# works only on Linux with good accuracy
# Windows needs another approach
time.sleep((utctime - datetime.datetime.utcnow()).total_seconds())
command = MaintRfc()
command.command = command.SET_CLOCK
command.data = (seconds, )
message.add_message(command)
self._handler.sendto(message)
LOG.debug("Time set to: %d = %s", seconds, utctime)

Creating loops to update a label in app jar

I'm trying to make a countdown timer in appJar and have a label that shows how much time is remaining until the end of the allotted amount of time. I've looked at the guides on appJar's website a fair amount and know of the two ways that they say you can create loops with their library. You can use .registerevent(function) or .after(delay_ms, function, *args). I've tried both of these ways and can't get either to work. I haven't managed to figure out how to get the .after function to work and every time I try to use the .registerevent function something doesn't work. My current issue is that I can get the function to run but it isn't actually working. That is, it says the block of code is running but the GUI ins't updating
Here are the specific lines of code in question
def introduction_bill(x):
global time_remaining, time_allotted
time_remaining = 120
time_allotted = 120
app.removeAllWidgets()
print("ran 'introduction_bill'")
app.addLabel('timer', 'Time remaining: 2:00')
app.addButtons(['start timer','update'], [start_timer, update_timer])
app.addButton('next introduction', next_introduction)
....
def update_timer():
global time_remaining, current_function
current_function = 'update timer'
time_remaining = end_time - t.time()
minutes = int(time_remaining // 60)
seconds = round(time_remaining % 60, 2)
app.setLabel('timer', 'Timer remaining: ' + str(minutes) + ':' + str(seconds))
print("ran 'update_timer'")
if time_remaining > -10:
app.registerEvent(update_timer)
def start_timer(x):
print("ran 'start_timer'")
global start_time, end_time
start_time = t.time()
end_time = start_time + time_allotted
update_timer()
And here is the code in its entirety
Keep in mind that I am still a beginner in coding so this code is both incomplete and very rough.
You can achieve what you want with both of the methods you mention.
With registerEvent() you should only call it once, it then takes care of scheduling your function. In your code, you are calling it repeatedly, which won't work.
With after() you have to take care of calling it again and again.
So, with your current code, you're better off using after():
In update_timer() try changing the call to app.registerEvent(update_timer) to be app.after(100, update_timer)
The timer should then update every 0.1 seconds.
However, if you click the Start Timer button again, you'll run into problems, so you might want to disable the button until the timer finishes.

How to prevent Execution usage limit in scheduled scripts

I am using the scheduled script which will create the custom records based on criteria. every time when the schedule script runs it should create approx. 100,000 records but the script is timing out after creating 5000 or 10000 records. I am using the below script to prevent the script execution usage limit but even with this also the script is not working. can any one please suggest some thing or provide any information. any suggestions are welcome and highly appreciated.
In my for loop iam using the below script. with this below script included the scheduled script is able to create up to 5000 or 10000 records only.
if (nlapiGetContext().getRemainingUsage() <= 0 && (i+1) < results.length )
{
var stateMain = nlapiYieldScript();
}
If you are going to reschedule using the nlapiYieldScript mechanism, then you also need to use nlapiSetRecoveryPoint at the point where you wish the script to resume. See the Help documentation for each of these methods, as well as the page titled Setting Recovery Points in Scheduled Scripts
Be aware that nlapiSetRecoveryPoint uses 100 governance units, so you will need to account for this in your getRemainingUsage check.
#rajesh, you are only checking the remaining usage. Also do check for execution time limit, which is 1 hour for any scheduled script. Something like below snippet-
var checkIfYieldOrContinue = function(startTime) {
var endTime = new Date().getTime();
var timeElapsed = (endTime * 0.001) - (startTime * 0.001);
if (nlapiGetContext().getRemainingUsage() < 3000 ||
timeElapsed > 3500) { //3500 secs
nlapiLogExecution('AUDIT', 'Remaining Usage: ' + nlapiGetContext().getRemainingUsage() + '. Time elapsed: ' + timeElapsed);
startTime = new Date().getTime();
var yieldStatus = nlapiYieldScript();
nlapiLogExecution('AUDIT', 'script yielded.' + yieldStatus.status);
nlapiLogExecution('AUDIT', 'script yielded reason.' + yieldStatus.reason);
nlapiLogExecution('AUDIT', 'script yielded information.' + yieldStatus.information);
}
};
Inside your for loop, you can call this method like-
var startTime = new Date();
if ((i+1) < results.length ) {
//do your operations here and then...
checkIfYieldOrContinue(startTime);
}
I have a script that lets you process an array like a forEach. The script checks each iteration and calculates the maximum usage and yields when there is not enough usage left to cover the max.
Head over to https://github.com/BKnights/KotN-Netsuite and download simpleBatch.js

Watir-webdriver hangs fro 1-2 minutes for "repeat" scenario

I have the next method in my page object:
def open_random_report(count)
opened_reports = 0
rows = self.how_many_reports_present
cells = self.browser.divs(:class=>/x-grid-cell-inner./)
type_position = self.calculate_report_type_position
row_length = 0
self.browser.divs(:class=>"x-column-header-inner").each do |d|
if d.visible?
row_length += 1
end
end
while opened_reports < count.to_i do
$start=Time.now
r = Random.new
row = r.rand(rows - 2)
cell_position = type_position + (row * row_length) - 1
cells[cell_position].a.click
opened_reports += 1
sleep 1
self.close_report
$finish=Time.now
p "#{$finish} Report# #{opened_reports} - #{$finish - $start}"
f = File.new('log.txt', 'a')
f.puts "#{$finish} Report# #{opened_reports} - #{$finish - $start}"
f.close
end
end
This code clicks on random cell in the table(table is represented by the extjs-grid) and it works ok except for one thing: from time to time driver hangs for 1-2 minutes. There is no pattern for hanging, it can happens one time during a run or may happen 10 times during the run.
One more detail: When driver click on cell the app generates pdf report that will be shown to the user in preview window. I don't care about the report my goal is just to open reports so I'm closing preview window despite that fact that pdf has already completely loaded or not.
Any ideas why such hanging may happen? Maybe there is some problem with code?

Resources