Run one function only once when the function starts everyday or some time period
5 次查看(过去 30 天)
显示 更早的评论
Hi,
I want to do this: with my login system, I only want it to run once when the user starts to use it everyday or some time let's say 5 hours etc... not everytime when people run the funtion you need to log in every time.
For example this login function is inside one big function, so everytime when you run this big function, it can only run the login once everyday. So even let's say I run the function 3 times within 5 minutes, I do not want to login every time I run. Only the first time is enough....I know a counter might work, like to change from 0 to 1, but then later how can I clear it next day? Or maybe PERSISTENT...anyone can help ?
thanks
2 个评论
Titus Edelhofer
2015-2-3
I have a rough idea what you want to achieve, but maybe you can give some more details ...? Would make giving a recommendation easier.
Titus
采纳的回答
Guillaume
2015-2-3
编辑:Guillaume
2015-2-4
Yes, use persistent and store the last time it was run in your variable. Then compare the current time to the stored time and if not enough time has elapsed just return from the function:
function login()
persistent rundate;
lastrun = rundate;
rundate = now;
if ~isempy(lastrun) && hours(datetime(rundate, 'ConvertFrom', 'datenum') - datetime(lastrun, 'ConvertFrom', 'datenum')) < 24
return;
end
%... normal content of login
end
7 个评论
Guillaume
2015-2-4
编辑:Guillaume
2015-2-4
Yes, it is in days. As I said you need to understand how datenum are constructed. The integral part is the number of days (since a reference time), the fractional is made up of hours/24 + minutes/(24*60) + seconds/(24*60*60) + milliseconds/(24*60*60*60).
The new datetime and duration types of R2014b make it much easier to extract a duration in whichever unit of time you want.
更多回答(1 个)
Titus Edelhofer
2015-2-3
Hi,
you mean something like this:
function Data()
l = login();
code of data processing....etc
function aLogin = login()
persistent theLogin
persistent lastLogin
if isempty(theLogin)
% first call
theLogin = doSomething;
lastLogin = now;
elseif (now-lastLogin) > 2 / 24
% if last login is more than two hours ago
theLogin = doSomething;
end
aLogin = theLogin;
end
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Calendar 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!