Monday, April 23, 2007

Run scheduled agent every 60 seconds

The shortest time between executions of a scheduled agent is 5 minutes. But very often you want to run some important function with only 1 minute interval. Your function takes maybe only 2 seconds to run, but you still are required to wait 5 minutes before it can be started again at the next agent invocation.

The agent I created makes it possible to simulate running agent every 60 seconds, or even every 2 seconds if you wish so. Some restrictions apply :)

It uses the fact that Notes counts 5 minutes from the START of the previous instance, not from the END. So if your agent takes 4 minutes 50 seconds to run, the next execution of the agent (assuming perfect conditions) will be just 10 seconds after the previous execution is finished. Delays caused by server load and other unforeseen delays can cause the agent to wait from 30 seconds to 2 minutes until the next execution. During many tests, I havent's observed execution delay longer than 2 minutes.

Even with the worst case 2 minutes delay, it's much better than standard 5 minutes delay. Note that this delay is only for the time between agent executions, within the started agent you can call the function every 2 seconds if you wish.

What if the function takes more than 5 minutes to run? Well, the next instance of the agent will wait until the current instance is finished and then start after a certain delay. In my tests the delay was almost always 2 minutes. The delay if the agent ends 15 seconds BEFORE the 5-minutes period (4m 45s) was according to my tests always 1 minute 5 seconds. These numbers will most certainly be somewhat different on your server.

The main disadvantage of this method is that one of the Agent Manager's threads will be constantly busy, so you would need to increase the number of agent threads to make it possible for other scheduled agents to run too.

To enable your agent to run every 60 seconds, do following:
1) In your existing agent, move the code from Initialize method to MainAction method.
2) Paste the code from the agent below into the Initialize method of your agent.
3) Change variable values as needed.

Agent is configured to execute the MainAction() function every 60 secondss (runinterval), max 100 times (runmaxtimes), during the 5 minute period (agentschedinterval).

Agent execution flow. Click to enlarge.

"Gone in 60 seconds" agent:

Sub Initialize
'Created by Andrei Kouvchinnikov,

Print "******************* Agent started *******************"

Dim session As New NotesSession
Dim db As NotesDatabase
Dim expectedruntime As Integer 'time which take to run the function. required only for deciding about ending the loop.
Dim runinterval As Integer 'interval (sec) between runs
Dim runmaxtimes As Integer ' max number of times the function will run
Dim runcounter As Integer 'counter of number of times the function run
Dim runstart As Long, runend As Long, rundiff As Long
Dim notimeleft ' loop must be closed now, no time left to run another round
Dim agentstart As Long 'initial time when agent started. required only for deciding about ending the loop.
Dim agentschedule As Integer 'nr of minutes this agent is scheduled to run. required only for deciding about ending the loop.
Dim dynadjust 'instead of hardcoded runtime value, use last run period for calculation of next period
Dim uselongestperiod 'instead of the last run period, use the longest period the function took to run

expectedruntime=10 ' function is initially expected to take max 10 seconds
runinterval=60 ' function is called with interval of X seconds
runmaxtimes=100 'if function's run time variates, you can limit max number of times function runs
agentschedinterval=5 'agent is scheduled to run every X minutes. From the agent properties.
margininterval=5 'nr of seconds to add to the final round. used for situations when function's execution time is 0.


While runcounter<runmaxtimes And notimeleft=False

Call MainAction()

If dynadjust=True Then expectedruntime=Int(runend-runstart) 'dynamically adjust expected time to actual time it take to run the function
If uselongestperiod Then
If expectedruntime<Int(runend-runstart) Then expectedruntime=Int(runend-runstart)
End If

If Int((agentschedinterval*60)-Int(Timer-agentstart))<timeleft+(expectedruntime+Int(expectedruntime/100*30)+margininterval) Then 'assumes that function can take 30% longer time to run than the last time
Print "Exit. Function will not manage to finish one more run. Computed time: "+Cstr(Now)+" + "+Cstr((expectedruntime+Int(expectedruntime/100*30)))
End If

If timeleft>0 And notimeleft=False Then
Sleep timeleft 'finished before the expected time. sleep until next execution.
Sleep Int((agentschedinterval*60)-Int(Timer-agentstart))-margininterval 'sleep X seconds-margin
End If
Print "******************* Agent finished *******************"
End Sub

Sub MainAction()
Print "Triggered "+Cstr(Now)

Here goes your code
Delete demo code below.

Sleep sleeprand 'Simulates time taken by the function's operations by sleeping X seconds

End Sub

This LotusScript was converted to HTML using the ls2html routine,
provided by Julian Robichaux at

Output from the agent. Note the 1m 5s delay between instances.



Anonymous said...

We can set the schedule option as "More than once a day" and ru agent every one minute ie. 60sec

Andrei Kouvchinnikov said...

You can type "1" in the minutes interval field in agent's scheduling properties, but it will be changed to "5" automatically by client/server.
Even if client/server does not change "1" to "5" (by using voodoo API mad l33t hax0r skillz), the agent will not run with 1 minute interval anyway, in the best case it will run with 5 minutes interval.
So unfortunately the type of solution described in the post is the only pure Domino solution.
You can also trigger agent every 1 minute using external Java/Windows program or calls to agent's URL, but that's another topic.

Anonymous said...

Your idea to schedule agent is very nice, but you wrote yourself, that the main disadvantage of this method is that one of the Agent Manager's threads will be constantly busy.

I have another idea to schedule an agent and you can set the delaytime e.g. to 10 seconds.

The idea:
1. Create an mail-in Database Document (e.g. mail-in name=Agentmail and the filename=yourdatabase.nsf

2. Create an BEFORE_MAIL_DELIVERY Agent "ControlAgent". To start the control-loop you only have to send a mail to "Agentmail".

The ControlAgent itself send a mail to "Agentmail" and in the subject field there are all the parameters, e.g. the last run from your productivity agent. When the current time is greater than the time you store in the subject field the ControlAgent starts your productivity agent with sendconsoleCommand "tell amgr run ..."

3. In my solution I have the parameter:
- counter (current)
- cycles (max. / 0=permanent)
- delayBetweenJobs
- mailaddress

Of course, the incoming mail will not be stored.

If you need detail information, please give me an answer here.

Best regards

Andrei Kouvchinnikov said...

Hi Didi. Let's say that you want to run the agent every 150 seconds. So you receive an email with "150 seconds" (or time value) as parameter. The last time agent run was 5 seconds ago. What is your code doing then? Sleeping 150 seconds and then sending console command and next mail to itself, or is it going into email loop and sends like 1 mail per second to itself until the specified time matches?


Anonymous said...

Hi Andrei,

the "lastJobTime" is a parameter in the email and the SendConsoleCommand is triggered by the difference between the "lastJobTime" and "now".

If difference>=delayBetweenJobs Then
Call session.SendConsoleCommand(<< ....... tell amgr run ...... >>)


'all parameters in field "subject"
'delimiter is "!@!"

maildoc.SendTo = mailaddressWatchDoc
maildoc.Subject = lastJobTime & "!@!" & Cstr(counter) & "!@!" & Cstr(cycles) & "!@!" & Cstr(delayBetweenJobs) & "!@!" & Cstr(delaySleep) & "!@!" & mailaddressWatchDoc

Call maildoc.Send( False )

end if


Hari said...

I like the idea. On going through the article, I thought it may be possible to implement this simpler: Say we estimate the agent we want to run to take 10 seconds per run. Have an agent that calls the agent we want to run repeatedly (with some sleep time), until it is about 4.30 minutes since the start of the calling agent.

A crude solution since it is not exactly a uniform interval, but easier to implement I thought. Any problems in this, except of course the need for an almost dedicated Agent Manager Thread?

Anonymous said...

Beautifull code, just what we needed !

Anonymous said...

Aston Villa rode their luck at Hull City where an 88-minute own goal from Kamil Zayatte saw them leapfrog three points clear of Arsenal and into fourth place in the Premier League wow gold with a 1-0 win.

Villa had to survive Hull penalty wotlk gold appeals for a handball against Ashley Young in time added on, television replays showing that referee Steve Bennett wow gold correctly rejected the claims after consulting a linesman.

Bennett had been involved in controversy after just five minutes when American goalkeeper Brad Friedel looked to have handed Hull the initiative and threaten Villa's return to the Champions League qualifying wow gold zone.

Friedel spilled the ball under pressure from Nick Barmby and stand-in right-back Nigel Reo-Coker turned it into his own net as he attempted to wow gold clear.

But Bennett cut short wow gold celebrations at the KC Stadium -- and let Friedel off the hook -- when he ruled out the score for an wow wotlkapparent infringement by Barmby.

Zayatte's intervention from a Young cross bound for wow gold Gabriel Agbonlahor then saw Villa leapfrog Arsenal and draw level with Manchester United on 38 points -- seven adrift of leaders Liverpool and four wow gold behind Chelsea.

Stung by an on-pitch dressing down wow gold by manager Phil Brown at Manchester City last week, Hull showed five changes and a vastly improved performance.

Promoted Hull were looking for only their second win in 11 games while wow gold Villa arrived unbeaten in seven and it looked to be heading for a goalless draw when the home side suffered a cruel late blow.

Anonymous said...

Premier League leaders Liverpool thrrew their "full support" world of warcraft gold behind Steven Gerrard after their captain was charged with assault on Tuesday following an incident at a local nightclub.

Gerrard, 28, and two other men were charged with assault occasioning bodily harm and affray, Merseyside police said.

They are scheduled to world of warcraft gold appear in court on January 23.

In the wake of the charges, Liverpool issued a wow power leveling statement on their official Web site.

"Steven has been an outstanding servant to Liverpool for the last ten years and the club will give him all the support he needs at this time," it read.

The offenses with which Gerrard have been charged carry a maximum penalty of five years in prison.

Three other men, who were also arrested, were world of warcraft gold released without charge pending further inquiries.

Gerrard was arrested cheap wow gold in the early hours of Monday morning and eventually charged after over 20 hours in police custody.

His wife Alex Curran was seen near the police station where world of warcraft gold he was held but drove off without talking to reporters.

Gerrard had been celebrating his side's 5-1 buy wow gold win over Newcastle on Sunday when the alleged altercation occurred.

He had scored two goals in the victory at St James' Park which left world of warcraft gold Liverpool top of the English Premier League and on course for their first English title in 18 years.

He was released on bail to wow power leveling appear in court on January 23 with John Doran, 29, and Ian Smith, 19, who were charged with the same offenses.

Gerrard, who has spent his entire career with Liverpool, world of warcraft gold is one of the most celebrated players in the club's history and renowned as a model professional.

In 2005 he lifted the European Cup -- Liverpool's fifth -- wow gold kaufen after a thrilling penalty shooting victory over AC Milan and turned down the advances of cash-rich Chelsea to stay with his local club.

The midfielder has also made 70 appearances for England, captaining his country on four occasions.

He was made an Member of the British Empire (MBE) last year and received an honorary fellowship from Liverpool's John Moores University.

Liverpool's next match is against Preston in the English FA Cup on Saturday, a game Gerrard was due to sit out because of suspension

Anonymous said...

Today is the gold für wow second day of 2009 ,world of warcraft gold it also a mesos special for me .cheap wow gold Because i have cheap maplestory mesos a chance to go to an english speech of LiYang and crazy to learn english follow him . He is a firendly,kindly person who make me feel gold kaufen What‘s more ,maple story mesos he very confidence .And he make me sure what he can do i also can do,as long as i make a determination and force myself to do it every second,Crazy just like him .wow geld I learn one setence from his book ever :maple story items If you want to succeed always force yourself to do more .I can't agree more with him .wow gold farmen To be honest ,when i was a littel girl i already fall in love with english.But what a pity i am poor in english ,Maple Story Account and it make me feel frustrating .So i want to give up many times ,but i can't as i still love it .So i tell mysefl :if you think you can you can wow leveling,and all your maple story power leveling hard work will pay power leveling Today i am very happy i can listien this wonderful speech of LiYang. I reap a great benifits from him .maple story money As he say :i am the best ,and every one can do it . world of warcraft power leveling Yes,i belive i can do it if i crazy as he

buy wow gold said...

When the Wow Gold wolf finally found the wow gold cheap hole in the chimney he crawled cheap wow gold down and KERSPLASH right into that kettle of water and that was cheapest wow gold the end of his troubles with the big bad wolf.
The next day the Buy Wow Goldlittle pig invited hisbuy gold wow mother over . She said "You see it is just as mttgamingI told you. The way to get along in the world is to do world of warcraft gold things as well as you can." Fortunately for that little pig, he buy cheap wow gold learned that lesson. And he just agamegold lived happily ever after!.

Anonymous said...

Do you like playing the game where you need to use shaiya gold, when you do not have shaiya money, you must borrow cheap shaiya gold from friends, or you can not go on this game without shaiya online gold. If you buy shaiya gold, you can continue this game.
Do you like playing the game where you need to use requiem gold, when you do not have requiem lant, you must borrow requiem money from friends, or you can not go on this game without cheap requiem lant. If you get requiem online gold, you can continue this game.

Best World of Warcraft Gold Guide said...

great post man :)

aion china said...

aion china,
aion china gold,
aion cn gold,
aion chinese gold,
aion gold china,
aion gold chinese,
china aion gold,
chinese aion gold,
aion china kina,
aion chinese kina,
aion kina china,
china aion kina,
aion china buy,
buy aion china,
aion chinese server gold,
aion cn server gold,
aion china server gold,
china aion server gold,
chinese aion server gold,
aion chinese server gold,
aion cn server kina,
aion china server kina,
china aion server kina,
chinese aion server kina

Anonymous said...

A slim, wide-eyed mygamegoldwoman almost human in virbanksfeatures eyed agamegold the pair. Her nose was sharp, but very elegant. She had tbcgold a pale, trade4gamebeautiful face the color of ivory, and veryge for hair she wore a wondrous mane of downy feathers. Her gown fluttered as she walked—on two delicate worldofgolds but still sharply-taloned feet. “Awake, awake you are,” she said with a pvp365 slight frown. “You should rest, rest.” Krasus bowed to her. “I am ezmmorpg grateful for your ighey hospitality, mistress, but I am well enough to continue on9a9z now.” She cocked her head as a bird might, giving the mageltk365 a reproving look. “No, no…too soon, toogold4guild soon. Please, sit.” The duo looked around u4game and discovered that two chairs, made in the same ready4game fashion as the nest, waited behind happygolds them. Malfurion waited for Krasus, who finally nodded and sat.

Aion gold said...

I like play online game, I also buy Aion gold and Aion gold, the Aion china gold is very cheap, and use the Aion China kina can buy many things, I like Aion chinese gold, thanks, it is very good.

Anonymous said...

find air beds in wisconsinbest air beds in wisconsincloud air beds

best cloud inflatable air bedssealy air beds portableportables air bedsrv luggage racksaluminum made rv luggage racksair bed raisedbest form raised air bedsbed air informercialsbest informercials bed airmattress sized air beds

bestair bed mattress antique doorknobsantique doorknob identification tipsdvd player troubleshootingtroubleshooting with the dvd playerflat panel television lcd vs plasmaflat panel lcd television versus plasma pic the bestadjustable bed air foam The best bed air foam

hoof prints antique equestrian printsantique hoof prints equestrian printsBuy air bedadjustablebuy the best adjustable air bedsair beds canadian storesCanadian stores for air beds

migraine causemigraine treatments floridaflorida headache clinicdrying dessicantair drying dessicant

Anonymous said...

black mold exposureblack mold symptoms of exposurewrought iron garden gatesiron garden gates find them herefine thin hair hairstylessearch hair styles for fine thin hairnight vision binocularsbuy night vision binocularslipitor reactionslipitor allergic reactionsluxury beach resort in the philippines

afordable beach resorts in the philippineshomeopathy for big with great mineral makeup bargainsmineral makeup wholesalersprodam iphone Apple prodam iphone prahacect iphone manualmanual for P 168 iphonefero 52 binocularsnight vision Fero 52 binocularsThe best night vision binoculars here

night vision binoculars bargainsfree photo albums computer programsfree software to make photo albumsfree tax formsprintable tax forms for free craftmatic air bedcraftmatic air bed adjustable info hereboyd air bedboyd night air bed lowest price

Anonymous said...

new houston house houston house txstains removal dyestains removal clothesstains removalteeth whiteningteeth whiteningbright teeth

jennifer grey nosejennifer nose jobscalebrities nose jobsWomen with Big NosesWomen hairstylesBig Nose Women, hairstyles

Anonymous said...

dessicant air dryerpediatric asthmaasthma specialistasthma children specialistcarpet cleaning dallas txcarpet cleaners dallascarpet cleaning dallas

vero beach vacationvero beach vacationsbeach vacation homes veroms beach vacationsms beach vacationms beach condosmaui beach vacationmaui beach vacationsmaui beach clubbeach vacationsyour beach vacationscheap beach vacations

bob hairstylebob haircutsbob layeredpob hairstylebobbedclassic bobCare for Curly HairTips for Curly Haircurly hair12r 22.5 best pricetires truck bustires 12r 22.5

washington new housenew house houstonnew house san antonionew house ventura

Anonymous said... : cheap polo shirts : polo shirt : lacoste polo shirts : ralph lauren polo shirts : wholesale polo shirts : Yellow Polo Shirt : Men's Polo Shirts : Wholesale Polo Shirts : polo shirts : Lacoste polo shirts : chaussure puma : chaussures puma : polo shirts

bing said... : chi hair straightener : chi flat iron : new polo shirts : cheap handbags : cheap bags : puma chaussures : chaussures puma : chaussure puma : Men's North Face : Women's North Face : hair straighteners : sexy lingerie store : cheap ugg boots : tattoo wholesale : men's clothing : women's clothing : cheap hair straighteners : cheap Lacoste polo shirts : cheap Lacoste polo shirts : 2009 nike shoes : new nike shoes : Women's max : Men's max 93 : nike shox : Nike air force : Nike air max 2003 : nike air max ltd : nike air max tn : Nike air rift : Nike air Yeezy : nike airmax : Nike air max 90 : Nike air max 97 : nike birds nest shoes : nike dunk : nike RT1 shoes : nike SB : nike shox shoes : Nike shox OZ shoes : Nike shox R2 shoes : Nike shox R3 shoes : Nike shox R4 shoes : Nike shox R5 shoes : Nike shox TL3 : nike trainers lovers : tennis rackets : Wilson tennis rackets : HEAD tennis rackets : Babolat tennis rackets

Anonymous said...

If on the other hand, you need a detailed manual, the instructions are there for you to access.

Anonymous said...

you are not our mother. She has a soft, pleasant voice, but your voice is rough, you are the wolf.

Anonymous said...

who has started the last 12 games in the absence of Yi Jianlian. "I know I've improved a ton defensively this season."

Blogger.jinbo said...

chi flat iron . we have best price and free shipping.Welcome to wholesale chi flat iron at

wo said...

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . I like it

wo said...

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. . . . . .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . good,very good!

wo said...

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. . . . . . . . . . . . . . . . . . .

This article is very good,I like it !

wo said...

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . good!good!

wo said...

. . . . .
. . . .
. . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
I like it,good,very good!

Anonymous said...

Let's choose a glasses frames
do you want a pair of prescription eyeglasses.
Buy progressive glasses.

Adi said...

Oes Tsetnoc one of the ways in which we can learn seo besides Mengembalikan Jati Diri Bangsa. By participating in the Oes Tsetnoc or Mengembalikan Jati Diri Bangsa we can improve our seo skills. To find more information about Oest Tsetnoc please visit my Oes Tsetnoc pages. And to find more information about Mengembalikan Jati Diri Bangsa please visit my Mengembalikan Jati Diri Bangsa pages. Thank you So much.
Oes Tsetnoc | Semangat Mengembalikan Jati Diri Bangsa

Anonymous said...

Your blog is very good, it's the best blog I've ever seen, thank you!
By the way, do you like polo shirts, which are very chic, especially the polo t shirts, I love them very much. I also like playing tennis rackets, it can keep healthy, what do you like to do? I'd like to introduce myself as the outlet of polo t shirts women, polo t shirts on sale, and polo t shirts for women. These products are our masterpieces, such as polo shirts on sale, polo shirts men, men's polo shirt, men polo shirt, mens polo shirts, mens polo shirt, besides we also sell cheap polo shirts, discount polo shirts, men's polo shirts, women's polo shirts. We are also the outlet of, cheap tennis racket, discount tennis racket, we recommend prince tennis racquet, head tennis rackets, wilson tennis racket, babolat tennis racquet. And it is our great pleasure that you come to our store online!

nurmanelis said...

hai.. ohhh it was incredible tool ... I was frankly very surprised and awesome .. taste in my country there? ... I wanted to follow up on the job ... ((once again good and I'm proud of such a tool maker) OCTOBER FALL Ι LOMBOK &BALI ISLAND

Roxy said...

Costa rica tours, shopping online, costa rica fishing, jaco fishing charters, costa rica whale watching, costa rica dolphin watching, costa rica party boat, panama fishing, fishing costa rica los suenos, los suenos fishing charters, costa rica fishing los suenos, los suenos costa rica fishing, costa rica los suenos fishing, fishing costa rica los suenos, los suenos fishing charters, costa rica fishing los suenos, los suenos costa rica fishing charters, costa rica los suenos fishing, Los suenos fishing, Fishing costa rica los suenos, Costa Rica Rafting,

alexander mcqueen shoes said...

Christian Louboutin Lima 120 sandals
christian louboutin Lima Buckled Velvet Sandal
Christian Louboutin lime green patent leather 'Noeudette' sandal
Christian Louboutin Mount Street Sandals (Noir)
Christian Louboutin Activa cork sandals

Christian Louboutin Alta Perla Strass 100 sandals
Christian Louboutin Carnaval Black

vibrams said...

The christian louboutin heels is designed for the ladies. Since the pumps was born, the ladies life become colorful. The christian louboutin evening pumps are the god's masterwork. Who invited thechristian louboutin pumps? Seldom people knew, but I think every lady would be grateful for him. Among the countless pumps, the christian louboutin peep toe is the most outstanding ones. The elegant pattern, the delicate style all mold the ladies perfect leg profile. Flowers in the spring of 2011 creeping, up from hair to clothes continue to footwear, have had a brilliant up. In such a glamor, spring and summer flowers now here. Romance is a woman's mood, exquisite flowers just right of expression in our gestures, the woman, how can we not love the romantic temperament so that they distributed the flowers do? 2011 flowers bloom will enjoy different poses! The Christian Louboutin 2011 Sandals also can adds the hright of the ladies, it bring surprise to the short lady. Especially the red sole of the louboutin heels, magic and sexy, many ladies are crazy. The red sole, the first feature of the Christian Louboutin stroe.