public void AddTimer(Timer timer, int callId, int actorId) { lock (_lock) { TimerInfo record = new TimerInfo { Timer = timer, CallId = callId, Actor = actorId }; _timersByCallId[callId] = record; } }
private void OnAddCommand() { var info = new TimerInfo { Name = String.Format("Timer {0}", _timers.Count) }; _timers.Add(new TimerViewModel(info)); }
// Add a timeout to expire in timeout_ milliseconds. After the // expiration timer_event on sink_ object will be called with // argument set to id_. public void AddTimer(long timeout, IPollEvents sink, int id) { long expiration = Clock.NowMs() + timeout; TimerInfo info = new TimerInfo(sink, id); if (!m_timers.ContainsKey(expiration)) m_timers.Add(expiration, new List<TimerInfo>()); m_timers[expiration].Add(info); }
public Task<ITriggerData> BindAsync(object value, ValueBindingContext context) { TimerInfo timerInfo = value as TimerInfo; if (timerInfo == null) { timerInfo = new TimerInfo(_attribute.Schedule); } IValueProvider valueProvider = new ValueProvider(timerInfo); IReadOnlyDictionary<string, object> bindingData = CreateBindingData(); return Task.FromResult<ITriggerData>(new TriggerData(valueProvider, bindingData)); }
public async Task<ITriggerData> BindAsync(object value, ValueBindingContext context) { TimerInfo timerInfo = value as TimerInfo; if (timerInfo == null) { ScheduleStatus status = null; if (_attribute.UseMonitor && _config.ScheduleMonitor != null) { status = await _config.ScheduleMonitor.GetStatusAsync(_timerName); } timerInfo = new TimerInfo(_attribute.Schedule, status); } IValueProvider valueProvider = new ValueProvider(timerInfo); IReadOnlyDictionary<string, object> bindingData = CreateBindingData(); return new TriggerData(valueProvider, bindingData); }
public void SetUp() { _containerMock = Substitute.For<IContainer>(); Program.Container = _containerMock; _textWriterMock = Substitute.For<TextWriter>(); var timerSchedule = Substitute.For<TimerSchedule>(); _timerInfoMock = Substitute.For<TimerInfo>(timerSchedule); _sitemapGeneratorServiceMock = Substitute.For<ISitemapGeneratorService>(); _containerMock.GetInstance<ISitemapGeneratorService>().Returns(_sitemapGeneratorServiceMock); _expectedJobResult = new RegenerateSitemapsJobResult { TimeElapsedInMilliseconds = 1000, NumberOfSitemapsGenerated = 20 }; _sitemapGeneratorServiceMock.RegenerateSitemaps().Returns(_expectedJobResult); }
public void SetTimerEvent(uint m_localID, UUID m_itemID, double sec) { if (sec == 0) // Disabling timer { UnSetTimerEvents(m_localID, m_itemID); return; } // Add to timer TimerInfo ts = new TimerInfo(); ts.localID = m_localID; ts.itemID = m_itemID; ts.interval = Convert.ToInt64(sec * 10000000); // How many 100 nanoseconds (ticks) should we wait // 2193386136332921 ticks // 219338613 seconds //ts.next = DateTime.Now.ToUniversalTime().AddSeconds(ts.interval); ts.next = DateTime.Now.Ticks + ts.interval; string key = MakeTimerKey(m_localID, m_itemID); // Adds if timer doesn't exist, otherwise replaces with new timer Timers[key] = ts; }
internal async Task InvokeJobFunction(DateTime lastOccurrence, bool isPastDue) { CancellationToken token = _cancellationTokenSource.Token; TimerInfo timerInfo = new TimerInfo(_attribute.Schedule); timerInfo.IsPastDue = isPastDue; TriggeredFunctionData input = new TriggeredFunctionData { // TODO: how to set this properly? ParentId = null, TriggerValue = timerInfo }; FunctionResult result = await _executor.TryExecuteAsync(input, token); if (!result.Succeeded) { token.ThrowIfCancellationRequested(); } if (_attribute.UseMonitor) { DateTime nextOccurrence = _schedule.GetNextOccurrence(lastOccurrence); await _scheduleMonitor.UpdateAsync(_timerName, lastOccurrence, nextOccurrence); } }
public static void RunKeepAlive([TimerTrigger("0 */1 * * * *")] TimerInfo timer, ExecutionContext ctx, ILogger log) { TraceExecution(ctx, log); }
internal async Task InvokeJobFunction(DateTime lastOccurrence, bool isPastDue = false) { CancellationToken token = _cancellationTokenSource.Token; TimerInfo timerInfo = new TimerInfo(_attribute.Schedule, _scheduleStatus, isPastDue); TriggeredFunctionData input = new TriggeredFunctionData { TriggerValue = timerInfo }; try { FunctionResult result = await _executor.TryExecuteAsync(input, token); if (!result.Succeeded) { token.ThrowIfCancellationRequested(); } } catch { // We don't want any function errors to stop the execution // schedule. Errors will be logged to Dashboard already. } if (ScheduleMonitor != null) { _scheduleStatus = new ScheduleStatus { Last = lastOccurrence, Next = _schedule.GetNextOccurrence(lastOccurrence) }; await ScheduleMonitor.UpdateStatusAsync(_timerName, _scheduleStatus); } }
public static Task TimerTrigger(TimerInfo timerInfo) { return Task.FromResult(0); }
public async static Task GetBusData([TimerTrigger("*/15 * * * * *")] TimerInfo myTimer, ILogger log) { var m = new BusDataManager(log); await m.ProcessBusData(); }
public static void Run([TimerTrigger("*/30 * * * * *")] TimerInfo myTimer, ILogger log) { log.LogInformation( $"DBCheckTimerTrigger - iniciando execução em: {DateTime.Now}"); var storageAccount = CloudStorageAccount .Parse(Environment.GetEnvironmentVariable("BaseLog")); var logTable = storageAccount .CreateCloudTableClient().GetTableReference("LogTable"); if (logTable.CreateIfNotExistsAsync().Result) { log.LogInformation("Criando a tabela de log..."); } var hosts = Environment.GetEnvironmentVariable("Sites") .Split("|", StringSplitOptions.RemoveEmptyEntries); foreach (string host in hosts) { log.LogInformation( $"Verificando a disponibilidade do host {host}"); var dadosLog = new LogEntity("MonitoramentoSites", DateTime.Now.ToString("yyyyMMddHHmmss")); dadosLog.Site = host; using (var client = new HttpClient()) { client.BaseAddress = new Uri(host); client.DefaultRequestHeaders.Accept.Clear(); try { // Envio da requisicao a fim de determinar se // o site esta no ar HttpResponseMessage response = client.GetAsync("").Result; dadosLog.Status = (int)response.StatusCode + " " + response.StatusCode; if (response.StatusCode != System.Net.HttpStatusCode.OK) { dadosLog.DescricaoErro = response.ReasonPhrase; } } catch (Exception ex) { dadosLog.Status = "Exception"; dadosLog.DescricaoErro = ex.Message; } } string jsonResultado = JsonSerializer.Serialize(dadosLog); if (dadosLog.DescricaoErro == null) { log.LogInformation(jsonResultado); } else { log.LogError(jsonResultado); } var insertOperation = TableOperation.Insert(dadosLog); var resultInsert = logTable.ExecuteAsync(insertOperation).Result; string jsonResultInsert = JsonSerializer.Serialize(resultInsert); log.LogInformation(jsonResultInsert); Thread.Sleep(3000); } log.LogInformation( $"ChecagemTimerTrigger - concluindo execução em: {DateTime.Now}"); }
public void CreateFromData(uint localID, UUID itemID, UUID objectID, Object[] data) { int idx = 0; while (idx < data.Length) { TimerInfo ts = new TimerInfo(); ts.localID = localID; ts.itemID = itemID; ts.interval = (long)data[idx]; ts.next = DateTime.Now.Ticks + (long)data[idx+1]; idx += 2; lock (TimerListLock) { Timers.Add(MakeTimerKey(localID, itemID), ts); } } }
public static void Run([TimerTrigger("0 */5 * * * *")] TimerInfo myTimer, ILogger log) { log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}"); }
// Add a timeout to expire in timeout_ milliseconds. After the // expiration timer_event on sink_ object will be called with // argument set to id_. public void AddTimer(long timeout, IPollEvents sink, int id) { long expiration = Clock.NowMs () + timeout; TimerInfo info = new TimerInfo(sink, id); m_timers.Add(expiration, info); }
/// <summary> /// ɾ����ʱ���¼� /// </summary> /// <param name="name"></param> public void RemoveTimerEvent(TimerInfo info) { if (objects.Contains(info) && info != null) { info.delete = true; } }
/// <summary> /// ������ʱ���¼� /// </summary> /// <param name="info"></param> public void ResumeTimerEvent(TimerInfo info) { if (objects.Contains(info) && info != null) { info.delete = false; } }
/// <summary> /// ��Ӽ�ʱ���¼� /// </summary> /// <param name="name"></param> /// <param name="o"></param> public void AddTimerEvent(TimerInfo info) { if (!objects.Contains(info)) { objects.Add(info); } }
/// <summary> /// ֹͣ��ʱ���¼� /// </summary> /// <param name="info"></param> public void StopTimerEvent(TimerInfo info) { if (objects.Contains(info) && info != null) { info.stop = true; } }
public static async Task Run([TimerTrigger("0 30 */2 * * *")] TimerInfo myTimer, TraceWriter log) { PostsToProcessQueueAdapter postsToProcessQueueAdapter = new PostsToProcessQueueAdapter(); postsToProcessQueueAdapter.Init(log); PostToGetQueueAdapter postToGetQueueAdapter = new PostToGetQueueAdapter(); postToGetQueueAdapter.Init(); PostsTableAdapter postsTableAdapter = new PostsTableAdapter(); postsTableAdapter.Init(log); using (HttpClient httpClient = new HttpClient()) { string apiKey = ConfigurationManager.AppSettings["TumblrApiKey"]; do { CloudQueueMessage message = await postToGetQueueAdapter.GetNextMessage(); if (message == null) { return; } PostToGet postToGet = JsonConvert.DeserializeObject <PostToGet>(message.AsString); string url = "https://api.tumblr.com/v2/blog/" + postToGet.Blogname + "/posts?id=" + postToGet.Id + "&api_key=" + apiKey; log.Info("Making request to: " + url); HttpResponseMessage response = await httpClient.GetAsync(url); if (response.IsSuccessStatusCode) { TumblrResponse <BlogPosts> tumblrResponse = await response.Content.ReadAsAsync <TumblrResponse <BlogPosts> >(); BlogPosts blogPosts = tumblrResponse.Response; if (blogPosts.Posts != null && blogPosts.Posts.Count > 0) { postsToProcessQueueAdapter.SendPostsToProcess(blogPosts.Posts); } await postToGetQueueAdapter.DeleteMessage(message); log.Info("Successfully fetched " + postToGet.Blogname + "/" + postToGet.Id + " and queued for processing"); } else { log.Error("Error getting post " + postToGet.Blogname + "/" + postToGet.Id + ": " + response.ReasonPhrase); if (response.ReasonPhrase.IndexOf("limit exceeded", StringComparison.OrdinalIgnoreCase) >= 0) { log.Error("Limit exceeded, exiting"); return; } else if (response.ReasonPhrase.IndexOf("not found", StringComparison.OrdinalIgnoreCase) >= 0) { log.Error("Not found, deleting message, marking post as Not Found"); postsTableAdapter.MarkPostNotFound(postToGet.Blogname, postToGet.Id); await postToGetQueueAdapter.DeleteMessage(message); } } } while (true); } }
private IReadOnlyDictionary<string, object> CreateBindingData(TimerInfo timerInfo) { Dictionary<string, object> bindingData = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase); bindingData.Add("TimerTrigger", DateTime.UtcNow.ToString()); return bindingData; }
TimerInfo CreateRepairDockTimerInfo(Grabacr07.KanColleWrapper.Models.RepairingDock dock) { if (dock.State == Grabacr07.KanColleWrapper.Models.RepairingDockState.Locked) { return null; } var timer = new TimerInfo(dock.Id) { Type = TimerType.Repair, IsTitleEnabled = true, }; if (dock.Ship != null) { timer.TimerTitle = string.Format("{0} Lv.{1}", dock.Ship.Info.Name, dock.Ship.Level); } if (dock.CompleteTime.HasValue) { timer.CompleteDate = dock.CompleteTime.Value.LocalDateTime; } return timer; }
// This function will get triggered/executed when a new message is written // on an Azure Queue called queue. /* public static void ProcessQueueMessage([QueueTrigger("queue")] string message, TextWriter log) * { * log.WriteLine(message); * }*/ public static void DownloadStatsFile([TimerTrigger("0 * * * * *", RunOnStartup = true)] TimerInfo timerInfo, TextWriter log) { log.WriteLine("Stats Downloader has started."); }
/// <summary> /// 送信キューに加える /// </summary> /// <param name="info"></param> void EnqueTimer(TimerInfo info, bool resetTimer = true) { if (info == null) { throw new ArgumentNullException("info"); } // タイマを停止 if (resetTimer) { timer_.Stop(); } // キューに追加 lock (lockObj_) { // 同じのあったら消す var item = timerQueue_.FirstOrDefault(x => x.Tag == info.Tag && x.Type == info.Type); if (item != null) { timerQueue_.Remove(item); } // 追加 timerQueue_.AddLast(info); } // タイマを再開 if (resetTimer) { timer_.Start(); } }
private static int Add(TimerInfo info) { lock (Timers) { var id = GenerateId(); Timers.Add(id, info); return id; } }
/// <inheritdoc/> public void OnStopTimer(TimerInfo info) { }
public async Task Run([TimerTrigger("0 30 21 * * *")] TimerInfo timer) { await report.ExecuteAsync(); }
public static void QueueTimer(string timerName, TimerCallback callback, object state, int dueTime, int period) { Trace("QueueTimer : " + timerName + " , dueTime = " + dueTime.ToString() + " , period=" + period.ToString()); Hashtable syncedTimersHash = Hashtable.Synchronized( TimersHash ); if(syncedTimersHash.Contains(timerName)) { throw new System.ArgumentException("The timer + " + timerName + " already queued"); } TimerInfo ti = new TimerInfo(timerName, state, callback, period); Timer timer = new Timer(new TimerCallback(TimerProc), ti, dueTime, period); syncedTimersHash[timerName] = timer; }
public TCL.CompletionCode cmdProc( Interp interp, TclObject[] argv ) { int i; Notifier notifier = (Notifier)interp.getNotifier(); Object info; if ( assocData == null ) { /* * Create the "after" information associated for this * interpreter, if it doesn't already exist. */ assocData = (AfterAssocData)interp.getAssocData( "tclAfter" ); if ( assocData == null ) { assocData = new AfterAssocData( this ); interp.setAssocData( "tclAfter", assocData ); } } if ( argv.Length < 2 ) { throw new TclNumArgsException( interp, 1, argv, "option ?arg arg ...?" ); } /* * First lets see if the command was passed a number as the first argument. */ bool isNumber = false; int ms = 0; if ( argv[1].InternalRep is TclInteger ) { ms = TclInteger.get( interp, argv[1] ); isNumber = true; } else { string s = argv[1].ToString(); if ( ( s.Length > 0 ) && ( System.Char.IsDigit( s[0] ) ) ) { ms = TclInteger.get( interp, argv[1] ); isNumber = true; } } if ( isNumber ) { if ( ms < 0 ) { ms = 0; } if ( argv.Length == 2 ) { /* * Sleep for at least the given milliseconds and return. */ long endTime = System.DateTime.Now.Ticks / 10000 + ms; while ( true ) { try { System.Threading.Thread.Sleep( ms ); return TCL.CompletionCode.RETURN; } catch ( System.Threading.ThreadInterruptedException e ) { /* * We got interrupted. Sleep again if we havn't slept * long enough yet. */ long sysTime = System.DateTime.Now.Ticks / 10000; if ( sysTime >= endTime ) { return TCL.CompletionCode.RETURN; } ms = (int)( endTime - sysTime ); continue; } } } TclObject cmd = getCmdObject( argv ); cmd.preserve(); assocData.lastAfterId++; TimerInfo timerInfo = new TimerInfo( this, notifier, ms ); timerInfo.interp = interp; timerInfo.command = cmd; timerInfo.id = assocData.lastAfterId; assocData.handlers.Add( timerInfo ); interp.setResult( "after#" + timerInfo.id ); return TCL.CompletionCode.RETURN; } /* * If it's not a number it must be a subcommand. */ int index; try { index = TclIndex.get( interp, argv[1], validOpts, "option", 0 ); } catch ( TclException e ) { throw new TclException( interp, "bad argument \"" + argv[1] + "\": must be cancel, idle, info, or a number" ); } switch ( index ) { case OPT_CANCEL: if ( argv.Length < 3 ) { throw new TclNumArgsException( interp, 2, argv, "id|command" ); } TclObject arg = getCmdObject( argv ); arg.preserve(); /* * Search the timer/idle handler by id or by command. */ info = null; for ( i = 0; i < assocData.handlers.Count; i++ ) { Object obj = assocData.handlers[i]; if ( obj is TimerInfo ) { TclObject cmd = ( (TimerInfo)obj ).command; if ( ( cmd == arg ) || cmd.ToString().Equals( arg.ToString() ) ) { info = obj; break; } } else { TclObject cmd = ( (IdleInfo)obj ).command; if ( ( cmd == arg ) || cmd.ToString().Equals( arg.ToString() ) ) { info = obj; break; } } } if ( info == null ) { info = getAfterEvent( arg.ToString() ); } arg.release(); /* * Cancel the handler. */ if ( info != null ) { if ( info is TimerInfo ) { ( (TimerInfo)info ).cancel(); ( (TimerInfo)info ).command.release(); } else { ( (IdleInfo)info ).cancel(); ( (IdleInfo)info ).command.release(); } SupportClass.VectorRemoveElement( assocData.handlers, info ); } break; case OPT_IDLE: if ( argv.Length < 3 ) { throw new TclNumArgsException( interp, 2, argv, "script script ..." ); } TclObject cmd2 = getCmdObject( argv ); cmd2.preserve(); assocData.lastAfterId++; IdleInfo idleInfo = new IdleInfo( this, notifier ); idleInfo.interp = interp; idleInfo.command = cmd2; idleInfo.id = assocData.lastAfterId; assocData.handlers.Add( idleInfo ); interp.setResult( "after#" + idleInfo.id ); break; case OPT_INFO: if ( argv.Length == 2 ) { /* * No id is given. Return a list of current after id's. */ TclObject list = TclList.newInstance(); for ( i = 0; i < assocData.handlers.Count; i++ ) { int id; Object obj = assocData.handlers[i]; if ( obj is TimerInfo ) { id = ( (TimerInfo)obj ).id; } else { id = ( (IdleInfo)obj ).id; } TclList.append( interp, list, TclString.newInstance( "after#" + id ) ); } interp.resetResult(); interp.setResult( list ); return TCL.CompletionCode.RETURN; } if ( argv.Length != 3 ) { throw new TclNumArgsException( interp, 2, argv, "?id?" ); } /* * Return command and type of the given after id. */ info = getAfterEvent( argv[2].ToString() ); if ( info == null ) { throw new TclException( interp, "event \"" + argv[2] + "\" doesn't exist" ); } TclObject list2 = TclList.newInstance(); TclList.append( interp, list2, ( ( info is TimerInfo ) ? ( (TimerInfo)info ).command : ( (IdleInfo)info ).command ) ); TclList.append( interp, list2, TclString.newInstance( ( info is TimerInfo ) ? "timer" : "idle" ) ); interp.resetResult(); interp.setResult( list2 ); break; } return TCL.CompletionCode.RETURN; }
private IReadOnlyDictionary<string, object> CreateBindingData(TimerInfo timerInfo) { Dictionary<string, object> bindingData = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase); bindingData.Add("TimerTrigger", DateTime.UtcNow.ToString()); // TODO: figure out if there is any binding data we need return bindingData; }
TimerInfo CreateExpeditionTimerInfo(Grabacr07.KanColleWrapper.Models.Fleet fleet) { if (fleet.Id == 1) { return null; } TimerInfo timer = new TimerInfo( TimerType.Expedition, fleet.Id); var expedition = fleet.Expedition; if (expedition != null && expedition.Mission != null) { timer.TimerTitle = expedition.Mission.Title; timer.IsTitleEnabled = true; if (expedition.ReturnTime.HasValue) { timer.CompleteDate = expedition.ReturnTime.Value.LocalDateTime; } } return timer; }
// use a timer trigger that will be invoked every 20 seconds to signal the end of the test // 20 seconds should give enough time for the receive call to complete as the TryTimeout being used is 10 seconds. public static void Run([TimerTrigger("*/20 * * * * *")] TimerInfo timer) { _eventWait.Set(); }
TimerInfo CreateShipbuildingTiemrInfo(Grabacr07.KanColleWrapper.Models.BuildingDock dock) { if (dock.State == Grabacr07.KanColleWrapper.Models.BuildingDockState.Locked) { return null; } TimerInfo timer = new TimerInfo(dock.Id) { Type = TimerType.Shipbuilding, IsTitleEnabled = true }; if (dock.Ship != null) { timer.TimerTitle = string.Format("{0} {1}", dock.Ship.ShipType.Name, dock.Ship.Name); } if (dock.CompleteTime.HasValue) { timer.CompleteDate = dock.CompleteTime.Value.LocalDateTime; } return timer; }
void Host_eventPluginChannelCommandReceived(string name, string channel, string command, string[] parameters) { // !timer add "Tea Timer" 1h10m10s if (command == "timer") { if (parameters.Length > 0) { switch (parameters[0]) { case "add": if (parameters.Length >= 3) { try { string timerName = parameters[1].Trim(new char[] { '"' }); string timeString = parameters[2]; string[] hourBits = timeString.Split('h'); string minuteString = hourBits.Length == 1 ? hourBits[0] : hourBits[1]; string[] minuteBits = minuteString.Split('m'); string secondString = minuteBits.Length == 1 ? minuteBits[0] : minuteBits[1]; string[] secondBits = secondString.Split('s'); string sHour = hourBits.Length == 1 ? null : hourBits[0]; string sMinute = minuteBits.Length == 1 ? null : minuteBits[0]; string sSecond = secondBits.Length == 1 ? null : secondBits[0]; DateTime endTime = DateTime.Now; if (sHour != null) endTime = endTime.AddHours(Convert.ToInt32(sHour)); if (sMinute != null) endTime = endTime.AddMinutes(Convert.ToInt32(sMinute)); if (sSecond != null) endTime = endTime.AddSeconds(Convert.ToInt32(sSecond)); TimerInfo newTimer = new TimerInfo(); newTimer.Channel = channel; newTimer.Username = name; newTimer.Name = timerName; newTimer.EndTime = endTime; newTimer.Expired = false; xLogger.Logger.WriteLine(String.Format("Now: {0}, Expiry: {1}", DateTime.Now.ToLongTimeString(), endTime.ToLongTimeString())); Timers.Add(newTimer); Host.PluginResponse(channel, String.Format("Your timer \"{0}\" with a duration of{1}{2}{3} has been added!", timerName, (sHour != null ? String.Format(" {0} hours", sHour) : ""), (sMinute != null ? String.Format(" {0} minutes", sMinute) : ""), (sSecond != null ? String.Format(" {0} seconds", sSecond) : ""))); } catch (Exception ex) { Host.PluginResponse(channel, String.Format("Error while adding timer: {0}", ex.Message)); } } break; } } } }
// Create a timer. public static IntPtr CreateTimer(int interval) { lock(typeof(SystemEvents)) { // Create the timer information block. TimerInfo info = new TimerInfo(); // Allocate a new timer identifier. if(timers == null) { timers = new ArrayList(); } int timerId = 0; while(timerId < timers.Count && timers[timerId] != null) { ++timerId; } if(timerId >= timers.Count) { timers.Add(info); } else { timers[timerId] = info; } // Initialize the timer information block. info.timerId = timerId; info.timer = new Timer(new TimerCallback(Timeout), info, interval, -1); // Return the timer identifier, and make sure // that it will never be zero. return new IntPtr(timerId + 1); } }
/// <inheritdoc/> public void OnCreateTimer(TimerInfo info) { // TODO: figure out how to graph timers when we have no "timer id" at this point... }