public void RunTimer() { StateObjClass StateObj = new StateObjClass(); StateObj.TimerCanceled = false; StateObj.SomeValue = 1; System.Threading.TimerCallback TimerDelegate = new System.Threading.TimerCallback(TimerTask); System.Threading.Timer TimerItem = new System.Threading.Timer(TimerDelegate, StateObj, 0, 3000); // Save a reference for Dispose. StateObj.TimerReference = TimerItem; CPacket msg = CPacket.create(); JsonObjectCollection collection = new JsonObjectCollection(); collection.Add(new JsonStringValue("PROTOCOL_ID", "PING")); msg.push(collection.ToString()); this.send(msg); if (SocketExtensions.IsConnected(this.socket)) { Console.WriteLine("true"); } else { StateObj.TimerReference.Change(Timeout.Infinite, Timeout.Infinite); //Change Console.WriteLine("false(("); } }
private void buttonPlay_Click(object sender, RoutedEventArgs e) { StreamReader file = new System.IO.StreamReader(textBoxFilename.Text); trafficBotState.TrafficBotMessages = new List <TrafficPositionReportMessage>(); string line; while ((line = file.ReadLine()) != null) { var data = line.Split(':'); trafficBotState.TrafficBotMessages.Add(new TrafficPositionReportMessage() { Sender = "ROBOT1", Latitude = double.Parse(data[0]), Longitude = double.Parse(data[1]), TrueAltitude = double.Parse(data[2]), PressureAltitude = double.Parse(data[3]), Groundspeed = double.Parse(data[4]), Heading = double.Parse(data[5]), BankAngle = double.Parse(data[6]), Pitch = int.Parse(data[7]) }); } file.Close(); buttonPlay.Content = "Playing..."; trafficBotState.MessageEnumerator = trafficBotState.TrafficBotMessages.GetEnumerator(); var timerDelegate = new System.Threading.TimerCallback(TimerTask); var timerItem = new System.Threading.Timer(timerDelegate, trafficBotState, 2000, 5000); trafficBotState.TimerReference = timerItem; }
public static void SysTimers() { for (int i = 0; i < 10; i++) { //System.Timers.Timer aTimer = new System.Timers.Timer(); //aTimer.Elapsed += new ElapsedEventHandler(StartJobOnTime); //// Set the Interval to 1 day //aTimer.Interval = 6; //aTimer.AutoReset = true; //aTimer.Enabled = true; //_jobTimers.Add(aTimer); System.Threading.TimerCallback tcb = new System.Threading.TimerCallback(StartJobOnTime); System.Threading.Timer t=new Timer(tcb,i,2000,10000); _jobTimers.Add(t); } Console.WriteLine("Press Enter to exit"); int j = Console.Read(); //Console.WriteLine(_jobTimers.Count); // clean up the resources for (int k = 0; k < 10; k++) { _jobTimers.ElementAt(k).Dispose(); } }
protected void StartService() { log.Info("->"); heartbeatinterval = Configuration.Instance.HeartbeatInterval * 1000; heartbeatduetime = Configuration.Instance.HeartbeatDuetime * 1000; log.Info("1->"); heartbeatcb = new System.Threading.TimerCallback(ProcessTimerEventHeartbeat); log.Info("2->"); isRunning = false; heartbeattimer = new System.Threading.Timer(heartbeatcb, null, heartbeatduetime, heartbeatinterval); log.Info("3->"); //////////////////////////////////////////////////////////////////////////////////////////// interval = Configuration.Instance.Interval * 60 * 1000; // in config interval is in mins duetime = Configuration.Instance.Duetime * 1000; log.Info("4->"); cb = new System.Threading.TimerCallback(ProcessTimerEvent); log.Info("5->"); timer = new System.Threading.Timer(cb, null, duetime, interval); log.Info("<-"); }
private void SetupJob() { _input = new TextBox(); _input.Multiline = true; _input.AcceptsReturn = true; _input.AcceptsTab = true; _input.ScrollBars = System.Windows.Forms.ScrollBars.Both; _input.Dock = DockStyle.Fill; _input.SelectionStart = 0; //Work-around for the AppendText bug. _input.TextChanged += new EventHandler(_input_TextChanged); _log = new TextBox(); _log.Font = new System.Drawing.Font("Courier New", 8.25f, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, 0); _log.Multiline = true; _log.AcceptsReturn = true; _log.AcceptsTab = true; _log.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; _log.Dock = DockStyle.Fill; _log.SelectionStart = 0; //Work-around for the AppendText bug. _log.ReadOnly = true; SetSubItem(Display.name, FileName); SetSubItem(Display.dir, DirectoryName); _buf = new Byte[512]; asyncCallback = new AsyncCallback(AsyncRead); asyncReadCallback = new AsyncReadCallback(InvokedAsyncRead); SetStatus(Status.idle); timerCallback = new System.Threading.TimerCallback(TimerTick); timerTickCallback = new TimerTickCallback(InvokedTimerTick); timer = new System.Threading.Timer(timerCallback, this, 0, 2000); }
private void RunReassess() { int time = 10000 * 3; //定义30秒一次 tTime.TimerCallback timerDelagete = new tTime.TimerCallback(ReassessCallback); threeadingTimer = new tTime.Timer(timerDelagete, null, time, time); }
public static void RunTimer() { StateObjClass StateObj = new StateObjClass(); StateObj.TimerCanceled = false; StateObj.SomeValue = 1; System.Threading.TimerCallback TimerDelegate = new System.Threading.TimerCallback(TimerTask); // Create a timer that calls a procedure every 2 seconds. // Note: There is no Start method; the timer starts running as soon as // the instance is created. System.Threading.Timer TimerItem = new System.Threading.Timer(TimerDelegate, StateObj, 2000, 2000); // Save a reference for Dispose. StateObj.TimerReference = TimerItem; // Run for ten loops. while (StateObj.SomeValue < 10) { // Wait one second. System.Threading.Thread.Sleep(1000); } // Request Dispose of the timer object. StateObj.TimerCanceled = true; }
private void AddTimerForMessage(Outlook.MailItem child) { try { TimeSpan expiryTimeFromSent; TimeSpan.TryParse(child.UserProperties[LottieDurationProperty].Value.ToString(), out expiryTimeFromSent); DateTime sentTime; DateTime.TryParse(child.UserProperties[ApproxSentTime].Value.ToString(), out sentTime); TimeSpan timeToNag = sentTime.Subtract(DateTime.Now) + expiryTimeFromSent; // If timer has expired or is set to go within the next minute, do it in a minute. - see below for the note on nagging while Outlook // is starting up loading e-mail which >might< contain a response! if (timeToNag.CompareTo(new TimeSpan(0, 1, 0)) < 1) { //Used to do the Nag immediately, but if someone is firing up Outlook and this goes before the email has been loaded.... // So now we're just going to nag in 1 minute timeToNag = new TimeSpan(0, 1, 0); } // Add a Timer to fire off the nag when appropriate Threading.TimerCallback nagCallBack = DoNag; Threading.Timer t = new Threading.Timer(nagCallBack, child, timeToNag, new TimeSpan(0)); // Keep a table of some id and the timers so that we can cancel it if the person does reply messagesAndTimers.Add(child.ConversationID, t); DebugBox("Scheduling nag for " + timeToNag.ToString()); } catch (Exception ex) { MessageBox.Show("Could not schedule followup for message " + child.Subject + "."); } }
public Scheduler(ListView _jobs) { jobs = _jobs; timerCallback = new System.Threading.TimerCallback(TimerTick); timerTickCallback = new TimerTickCallback(InvokedTimerTick); timer = new System.Threading.Timer(timerCallback, this, 0, 200); }
private void connectButton_Click(object sender, EventArgs e) { ChangeControlState(false); try { CloseSession(); //Open session to the switch module and sets topology InitializeSwitchSession(); //Connect channel1 and channel2. //switchSession.Path.DisconnectAll(); Reset(); //List<string> pathList = new List<string> (); //switchSession.Path.SetPath(pathList); // Wait for any relay to activate and debounce. switchSession.Path.WaitForDebounce(maxTime); whichState = 1; relayCallback = new System.Threading.TimerCallback(SwitchState); relayTimer = new System.Threading.Timer(relayCallback, null, 1500, System.Threading.Timeout.Infinite); } catch (System.Exception ex) { ShowError(ex.Message); } finally { ChangeControlState(true); //Close session to switch module. //CloseSession(); } }
private void RunTimer(int CodigoCliente) { try { ClienteMutexInfo StateObj = new ClienteMutexInfo(); StateObj.TimerCanceled = false; StateObj.SomeValue = 1; StateObj.IdCliente = CodigoCliente; StateObj.StatusProcessando = EnumProcessamento.LIVRE; StateObj.FirstTimeProcessed = DateTime.Now; System.Threading.TimerCallback TimerDelegate = new System.Threading.TimerCallback(TimerTask); gLogger.Debug("Inicia timer para cliente [" + CodigoCliente + "] com [" + IntervaloRecalculo + "] ms"); System.Threading.Timer TimerItem; TimerItem = new System.Threading.Timer(TimerDelegate, StateObj, 1000, IntervaloRecalculo); StateObj.TimerReference = TimerItem; if (htClientes.ContainsKey(CodigoCliente)) { htClientes.TryRemove(CodigoCliente, out StateObj); } htClientes.AddOrUpdate(CodigoCliente, StateObj, (key, oldValue) => StateObj); } catch (Exception ex) { gLogger.Info("Ocorreu um erro no método RunTimer ", ex); } }
public ClientForServer() { GetMessageFromServer = new AddMessageDelegate(AsyncReceiveMessage); System.Threading.TimerCallback timerCallback = new System.Threading.TimerCallback(timerCallbackMethod); timer = new System.Threading.Timer(timerCallback, null, System.Threading.Timeout.Infinite, TimerTickPeriod); }
/// <summary> /// 启动服务器程序,开始监听客户端请求 /// </summary> public virtual void Start() { if (_isRun) { throw (new ApplicationException("TcpSvr已经在运行.")); } _sessionTable = new Hashtable(_maxClient); _recvDataBuffer = new byte[DefaultBufferSize]; //初始化socket _svrSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //绑定端口 IPEndPoint iep = new IPEndPoint(IPAddress.Any, _port); _svrSock.Bind(iep); //开始监听 _svrSock.Listen(5); //设置异步方法接受客户端连接 _svrSock.BeginAccept(new AsyncCallback(AcceptConn), _svrSock); _isRun = true; timerCB = new System.Threading.TimerCallback(CheckClient); timer = new Timer(timerCB, null, 10000, 1000); }
/// <summary> /// Обработка нажатия кнопки "GO" /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Mf_goBtn_Click(object sender, EventArgs e) { if (mf_tb_procName.Text == "") { Error("Ошибка! Вы не ввели процесс!"); return; } procName = mf_tb_procName.Text; procProp = mf_tb_procParam.Text; if (mf_cb_plan.Checked == true && mf_cb_fin.Checked == true) { Thr.TimerCallback callback = new Thr.TimerCallback(StopProc); eventTimer = new Thr.Timer(callback); if (mf_dp_date.Value > mf_dp_time.Value) { StartTimer(mf_dp_date.Value, mf_dp_time.Value, true); } else { StartTimer(mf_dp_time.Value, mf_dp_date.Value, true); } } else if (mf_cb_plan.Checked == true) { Thr.TimerCallback callback = new Thr.TimerCallback(StartProc); eventTimer = new Thr.Timer(callback); if (mf_dp_date.Value > mf_dp_time.Value) { StartTimer(mf_dp_date.Value, mf_dp_time.Value, false); } else { StartTimer(mf_dp_time.Value, mf_dp_date.Value, false); } } else if (mf_cb_fin.Checked == true) { Process pr = GetProcessByName(procName); if (pr != null) { StopProcess(pr); } else { Error($"Требуемый процесс {procName} - не найден!"); } } else { StartProcess(procName, procProp); } }
/// <summary> /// Starts the message poller. /// </summary> private void StartPoller() { StopPoller(); // Check for message every 5 seconds, starting now System.Threading.TimerCallback messagePollerDelegate = new System.Threading.TimerCallback(PollMessages); messagePoller = new System.Threading.Timer(messagePollerDelegate, null, 0, DefaultPollingInterval); }
static void Main(string[] args) { Game g = new Game(); System.Threading.TimerCallback timerCallback = g.TickTock; Timer tmr = new Timer(timerCallback, null, 1000, g.refreshRate); Console.ReadLine(); }
public JobDestinationDlg() { Init(); PopulateCombobox(); //udp = new udp(); timerCallback = new System.Threading.TimerCallback(TimerTick); timer = new System.Threading.Timer(timerCallback, this, Timeout.Infinite, 0); }
private void frmmain_Load(object sender, System.EventArgs e) { mcname = "."; presentprocdetails = new Hashtable(); LoadAllProcessesOnStartup(); System.Threading.TimerCallback timerDelegate = new System.Threading.TimerCallback(this.LoadAllProcesses); t = new System.Threading.Timer(timerDelegate, null, 1000, 1000); }
private async void Schedule(System.Threading.CancellationToken ct, System.Threading.TimerCallback recCb, int interval) { await Task.Delay(interval); if (_isActive) { recCb.Invoke(null); } }
public RemoteJobsOverview() { Init(); this.remoteJobsLV.Columns.Add("Server load", this.remoteJobsLV.Width, System.Windows.Forms.HorizontalAlignment.Left); startupThread = new Thread(new ThreadStart(ClientConnect)); timerCallback = new System.Threading.TimerCallback(TimerTick); timer = new System.Threading.Timer(timerCallback, this, Timeout.Infinite, 0); startupThread.Start(); }
public void StopAndDisposeWork() { this.timer.Dispose(); this.sb = null; if (cmd != null) { this.cmd.Dispose(); this.cmd = null; } this.tm_WorkThread_Callback = null; }
public ResourcesManager() { m_vDatabase = new DatabaseManager(); m_vClients = new ConcurrentDictionary<long,Client>(); m_vOnlinePlayers = new List<Level>(); m_vInMemoryLevels = new ConcurrentDictionary<long,Level>(); m_vTimerCanceled = false; System.Threading.TimerCallback TimerDelegate = new System.Threading.TimerCallback(ReleaseOrphans); System.Threading.Timer TimerItem = new System.Threading.Timer(TimerDelegate, null, 40000, 40000); TimerReference = TimerItem; }
public ResourcesManager() { m_vDatabase = new DatabaseManager(); m_vClients = new ConcurrentDictionary <long, Client>(); m_vOnlinePlayers = new List <Level>(); m_vInMemoryLevels = new ConcurrentDictionary <long, Level>(); m_vTimerCanceled = false; System.Threading.TimerCallback TimerDelegate = new System.Threading.TimerCallback(ReleaseOrphans); System.Threading.Timer TimerItem = new System.Threading.Timer(TimerDelegate, null, 60000, 60000); TimerReference = TimerItem; }
public WorkThread(System.Data.DataTable tVals) { this.lastSuccessTransaction = System.DateTime.MinValue; this._tVals = tVals; this.InitSql(); this.tsPeriod = new System.TimeSpan(600000000L); this.tm_WorkThread_Callback = new System.Threading.TimerCallback(this.tm_workthread_proc); this.CalcStart(); this.timer = new System.Threading.Timer(this.tm_WorkThread_Callback, this, this.tsStart, this.tsPeriod); System.Console.WriteLine("Запуск задачи произойдет через {0}", this.tsStart); }
internal void Start(System.Threading.TimerCallback recCb, int interval) { if (this._isActive) { throw new Exception("reconnector already scheduled"); } this.callback = recCb; this.interval = interval; Schedule(cts.Token, recCb, interval); this._isActive = true; }
private void tabControl1_SelectedIndexChanged(object sender, System.EventArgs e) { if (tabControl1.SelectedIndex == 1) { System.Threading.TimerCallback timerDelegate = new System.Threading.TimerCallback(this.LoadAllMemoryDetails); tclr = new System.Threading.Timer(timerDelegate, null, 0, 1000); } else { tclr.Dispose(); } }
public void RunTimer() { if (timeronrun == false) { timeronrun = true; StateObjClass StateObj = new StateObjClass(); StateObj.TimerCanceled = false; StateObj.SomeValue = 1; System.Threading.TimerCallback TimerDelegate = new System.Threading.TimerCallback(TimerTask); System.Threading.Timer TimerItem = new System.Threading.Timer(TimerDelegate, StateObj, 1000, 1000); StateObj.TimerReference = TimerItem; } }
public Form1() { InitializeComponent (); s.Rand ( 1000 ); s.Badd ( part ); this.Form1_ResizeEnd ( null, null ); tcb = kphyssolve; kphystimer = new System.Threading.Timer ( tcb, null, 0, 60 ); cgtcb = kcgsolve; kcgtimer = new System.Threading.Timer ( cgtcb, null, 0, 100 ); }
public PrepareNoteForm(NetworkNode client, string dbConnectionString, Log log) { this.client = client; this.dbConnectionString = dbConnectionString; this.log = log; InitializeComponent(); this.updateServerDelegate = new VoidDelegate(UpdateCurrentServerDetails); this.receiveHandler = new MessageEventHandler(client_MessageReceived); this.toggleSendButtonDelegate = new ButtonStringBoolDelegate(ToggleButton); this.closeDelegate = new DialogResultDelegeate(DoClose); this.timeDelegate = new VoidDelegate(UpdateTime); this.clockCallback = new System.Threading.TimerCallback(ClockTimerTimedout); }
public void StartWorkTimer() { object obj = null; System.Threading.TimerCallback TimerDelegate2 = new System.Threading.TimerCallback(PrintCappedFrames); TimerItem2 = new System.Threading.Timer(TimerDelegate2, obj, 0, 1000); // Create a timer that calls a procedure every 2 seconds. // Note: There is no Start method; the timer starts running as soon as // the instance is created. /*System.Threading.TimerCallback TimerDelegate = new System.Threading.TimerCallback(TimerTask); * int ms = 1000 / fps; * TimerItem = new System.Threading.Timer(TimerDelegate, obj, 0, ms);*/ }
///<MemberName>clsSerialCommunication</MemberName> ///<MemberType>Constructor</MemberType> ///<CreatedBy>Shubham</CreatedBy> ///<CommentedBy>Shubham</CommentedBy> ///<Date>12/05/2017</Date> ///<summary> /// This is constructor of the class. ///</summary> ///<ClassName>clsSerialCommunication</ClassName> public clsSerialCommunication() { //imBaudRate = 57600; comPort = new SerialPort(); comPort.DataBits = 8; comPort.Parity = Parity.None; comPort.DataReceived -= new SerialDataReceivedEventHandler(comPort_DataReceived); comPort.DataReceived += new SerialDataReceivedEventHandler(comPort_DataReceived); tmrCallback = new System.Threading.TimerCallback(MbTimerIntr); tmrMbTimer = new System.Threading.Timer(tmrCallback, null, 200, 200); tmrTimeoutCallback = new System.Threading.TimerCallback(TimeOutIntr); tmrTimeOut = new System.Threading.Timer(tmrTimeoutCallback, null, 10000, 10000); }// End of Constructor.
// Attributes // Methods public Config.status_t setAlarm(Alarm alarm, DateTime alarmDate) { System.Threading.TimerCallback cb = new System.Threading.TimerCallback(alarm.trigger); System.Threading.Timer timer = new System.Threading.Timer(cb); DateTime now = DateTime.Now; DateTime dateAlarm = alarmDate; int msUntilAlarm = (int)(dateAlarm - now).TotalMilliseconds; timer.Change(msUntilAlarm, Timeout.Infinite); return(Config.status_t.OK); }
protected override void OnLoad(EventArgs e) { base.OnLoad (e); GL.ClearColor (Color.MidnightBlue); GL.Enable (EnableCap.DepthTest); GL.Ortho (0, 1424, 0, 800, -1.0, 1.0); this.s.Rand (1000); this.s.Badd (this.part); tcb = kphyssolve; kphystimer = new System.Threading.Timer (tcb, null, 0, 60); //cgtcb = kcgsolve; //kcgtimer = new System.Threading.Timer (cgtcb, null, 0, 100); }
public void RunTimer() { StateObj.TimerCanceled = false; MainApp.GetDBConnection().connectToDB(MainApp.getProperties().getServer(), MainApp.getProperties().getDatabase(), MainApp.getProperties().getUser(), MainApp.getProperties().getPassword()); System.Threading.TimerCallback TimerDelegate = new System.Threading.TimerCallback(TimerTask); // Start timer run every 12 hours log.Info("Starting timer with delay: " + delay + ", interval: " + interval); System.Threading.Timer TimerItem = new System.Threading.Timer(TimerDelegate, StateObj, delay, interval); StateObj.TimerReference = TimerItem; }
private void DrawVideoBackground() { Thread.Sleep(_videoPlaybackSpeed); Bitmap _currentVideoBackground = null; if (_needToBuffer == false) { //get current video background _currentVideoBackground = m_VideoTextureManager.FrameQueue.Dequeue(); } else { if (_bufferTimerActive == false) { _bufferTimerActive = true; System.Threading.TimerCallback tcb = new System.Threading.TimerCallback(CancelNeedToBuffer); bufferTimer = new System.Threading.Timer(tcb, null, 3000, System.Threading.Timeout.Infinite); } } //if succeeded in getting background, draw it to screen. if (_currentVideoBackground != null) { //save current background so that it can be redrawn if queue is empty. _prevVideoBackground = new Bitmap(_currentVideoBackground); DrawBitmapToScreen(_currentVideoBackground); } else //have been unable to get next frame (because buffer is empty) { //if previous frame is valid if (_prevVideoBackground != null) { _needToBuffer = true; DrawBitmapToScreen(_prevVideoBackground); } } }
private void menuItem7_Click(object sender, System.EventArgs e) { try { string caption = "Enter Machine Name"; objnewprocess = new frmnewprcdetails(caption); if (objnewprocess.ShowDialog() != DialogResult.Cancel) { t.Dispose(); presentprocdetails.Clear(); lvprocesslist.Items.Clear(); LoadAllProcessesOnStartup(); if (frmmain.mcname == ".") { frmmain.objtaskmgr.Text = "Task Manager Connected to Local"; menuItem3.Visible = true; menuItem9.Visible = true; menuItem2.Visible = true; menuItem10.Visible = true; } else { frmmain.objtaskmgr.Text = "Task Manager Connected to " + frmmain.mcname; menuItem3.Visible = false; menuItem9.Visible = false; menuItem2.Visible = false; menuItem10.Visible = false; } System.Threading.TimerCallback timerDelegate = new System.Threading.TimerCallback(this.LoadAllProcesses); t = new System.Threading.Timer(timerDelegate, null, 1000, 1000); } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
public Form1() { InitializeComponent (); s.Rand ( 1000 ); s.Badd ( part ); bmp = new Bitmap ( (int)s.size.x, (int)s.size.y ); g = Graphics.FromImage ( bmp ); this.Form1_ResizeEnd ( null, null ); //kphysthread = new Thread(kphysthreadstart); //kphysthread.IsBackground = true; //kphysthread.Priority = ThreadPriority.Highest; //kphysthread.Start(); tcb = kphyssolve; kphystimer = new System.Threading.Timer ( tcb, null, 0, 60 ); cgtcb = kcgsolve; kcgtimer = new System.Threading.Timer ( cgtcb, null, 0, 100 ); // dtcb = kdraw; //kdrawtimer = new System.Threading.Timer(dtcb, null, 10, 100); /*kcgthread = new Thread(kcgthreadstart); kcgthread.IsBackground = true; kcgthread.Start();*/ g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Low; g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighSpeed; g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighSpeed; g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighSpeed; g.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceCopy; //s.cg.csubd(4); }
private void buttonPlay_Click(object sender, RoutedEventArgs e) { StreamReader file = new System.IO.StreamReader(textBoxFilename.Text); trafficBotState.TrafficBotMessages = new List<TrafficPositionReportMessage>(); string line; while((line = file.ReadLine()) != null) { var data = line.Split(':'); trafficBotState.TrafficBotMessages.Add(new TrafficPositionReportMessage() { Sender = "ROBOT1", Latitude = double.Parse(data[0]), Longitude = double.Parse(data[1]), TrueAltitude = double.Parse(data[2]), PressureAltitude = double.Parse(data[3]), Groundspeed = double.Parse(data[4]), Heading = double.Parse(data[5]), BankAngle = double.Parse(data[6]), Pitch = int.Parse(data[7]) }); } file.Close(); buttonPlay.Content = "Playing..."; trafficBotState.MessageEnumerator = trafficBotState.TrafficBotMessages.GetEnumerator(); var timerDelegate = new System.Threading.TimerCallback(TimerTask); var timerItem = new System.Threading.Timer(timerDelegate, trafficBotState, 2000, 5000); trafficBotState.TimerReference = timerItem; }
static void Main() { myThread = new Thread(func); //Создаем новый объект потока (Thread) myThreadClient = new Thread(funcClient); //Создаем новый объект потока (Thread) cb = new System.Threading.TimerCallback (ProcessTimerEvent); time = new System.Threading.Timer(cb, null, 0, 1000); System.IO.File.Delete(@".\report.xml"); System.IO.File.Delete(@".\powerGraph.jpg"); System.IO.File.Delete(@".\extGraph.jpg"); myThread.Start(); //запускаем поток myThreadClient.Start(); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new openForm()); web.stop(); myThread.Abort(); myThreadClient.Abort(); }
private void startCommunicatingTimer() { const int timeout = 500; // 250ms is too short. 500ms works well. lock (_isCommunicatingTimer_lock) { if (_isCommunicatingTimer == null) { // Set up timer. System.Threading.TimerCallback timerDelegate = new System.Threading.TimerCallback(_isCommunicatingTimer_Elapsed); _isCommunicatingTimer = new System.Threading.Timer(timerDelegate, null, timeout, System.Threading.Timeout.Infinite); OnCommunicationStarted(); } else // extend timer _isCommunicatingTimer.Change(timeout, System.Threading.Timeout.Infinite); } }
public WebsiteBetQueueTabControl() { this.InitializeComponent(); this.LoadLanguageFile(); _tmrSpliderCallback = new TimerCallback(this.tmrSpider_Tick); }
private void DrawVideoBackground() { Thread.Sleep(_videoPlaybackSpeed); Bitmap _currentVideoBackground=null; if (_needToBuffer == false) { //get current video background _currentVideoBackground = m_VideoTextureManager.FrameQueue.Dequeue(); } else { if (_bufferTimerActive == false) { _bufferTimerActive = true; System.Threading.TimerCallback tcb = new System.Threading.TimerCallback(CancelNeedToBuffer); bufferTimer = new System.Threading.Timer(tcb, null, 3000, System.Threading.Timeout.Infinite); } } //if succeeded in getting background, draw it to screen. if (_currentVideoBackground != null) { //save current background so that it can be redrawn if queue is empty. _prevVideoBackground = new Bitmap(_currentVideoBackground); DrawBitmapToScreen(_currentVideoBackground); } else //have been unable to get next frame (because buffer is empty) { //if previous frame is valid if (_prevVideoBackground != null) { _needToBuffer = true; DrawBitmapToScreen(_prevVideoBackground); } } }
/// <summary> /// Attempts to open a connection if there is currently no connection open, and starts the connection monitor. The ConnectionEstablished event occurs when the connection is established, and the ConnectionAttemptFailed event occurs when a connection attempt fails. /// No Exceptions are thrown. /// The first connection attempt blocks the thread so the Connected property should be checked after invoking StartConnectionMonitor() to determine if the inital connection attempt failed. /// </summary> public virtual void StartConnectionMonitorSync() { try { if (_isConnected == false) OnConnectionAttempt(); // this will call the highest level overridden method, so if it is overridden then the override will be called instead of the method in this class. } catch { // don't throw an error if it fails since we start the connection monitor below. } // Check if OnConnectionAttemptFailed() or OnConnectionEstablished() disposed the conneciton. // This is typical when first starting up and the connection fails, the app might dispose the object so the user can change the name. if (_disposed) return; // don't start up the connection monitoring since the object was disposed. //System.Diagnostics.Debug.WriteLine(DateTime.Now.ToString() + "************************************** StartConnectionMonitor Setting timer interval to " + _connectionAttemptInterval); if (_connectionMonitorTimer == null) { //System.Diagnostics.Debug.WriteLine(DateTime.Now.ToString() + "************************************** _connectionMonitorTimer is null, creating new timer."); // Set up dropped connection check timer. System.Threading.TimerCallback timerDelegate = new System.Threading.TimerCallback(_connectionMonitorTimer_Elapsed); _connectionMonitorTimer = new System.Threading.Timer(timerDelegate, null, _connectionAttemptInterval, System.Threading.Timeout.Infinite); } else _connectionMonitorTimer.Change(_connectionAttemptInterval, System.Threading.Timeout.Infinite); //System.Diagnostics.Debug.WriteLine(DateTime.Now.ToString() + "************************************** _connectionMonitorTimer has been set."); _connectionMonitorEnabled = true; }
private void checkBoxAutoCopy_CheckedChanged(object sender, EventArgs e) { if (checkBoxAutoCopy.Checked == true) { System.Threading.TimerCallback TimerDelegate = new System.Threading.TimerCallback(TimerTask); // Create a timer that calls a procedure every int.Parse(textBoxBackupTimeAuto.Text) seconds. // Note: There is no Start method; the timer starts running as soon as // the instance is created. if (string.IsNullOrEmpty(textBoxBackupTimeAuto.Text)) return; int minute = int.Parse(textBoxBackupTimeAuto.Text) * 1000 * 60; TimerItem = new System.Threading.Timer(TimerDelegate, null, minute, minute); } else { if (TimerItem != null) TimerItem.Dispose(); } }
public void ClientOnParcelFreezeUser(IClientAPI client, UUID parcelowner, uint flags, UUID target) { ScenePresence targetAvatar = null; ((Scene)client.Scene).TryGetScenePresence(target, out targetAvatar); ScenePresence parcelManager = null; ((Scene)client.Scene).TryGetScenePresence(client.AgentId, out parcelManager); System.Threading.Timer Timer; if (targetAvatar.UserLevel == 0) { ILandObject land = ((Scene)client.Scene).LandChannel.GetLandObject(targetAvatar.AbsolutePosition.X, targetAvatar.AbsolutePosition.Y); if (!((Scene)client.Scene).Permissions.CanEditParcelProperties(client.AgentId, land, GroupPowers.LandEjectAndFreeze)) return; if (flags == 0) { targetAvatar.AllowMovement = false; targetAvatar.ControllingClient.SendAlertMessage(parcelManager.Firstname + " " + parcelManager.Lastname + " has frozen you for 30 seconds. You cannot move or interact with the world."); parcelManager.ControllingClient.SendAlertMessage("Avatar Frozen."); System.Threading.TimerCallback timeCB = new System.Threading.TimerCallback(OnEndParcelFrozen); Timer = new System.Threading.Timer(timeCB, targetAvatar, 30000, 0); Timers.Add(targetAvatar.UUID, Timer); } else { targetAvatar.AllowMovement = true; targetAvatar.ControllingClient.SendAlertMessage(parcelManager.Firstname + " " + parcelManager.Lastname + " has unfrozen you."); parcelManager.ControllingClient.SendAlertMessage("Avatar Unfrozen."); Timers.TryGetValue(targetAvatar.UUID, out Timer); Timers.Remove(targetAvatar.UUID); Timer.Dispose(); } } }
private void Start() { System.Threading.TimerCallback timerCallback = new System.Threading.TimerCallback(timerCallbackMethod); timer = new System.Threading.Timer(timerCallback, null, System.Threading.Timeout.Infinite, TimerTickPeriod); }
//==================================================================================================== protected void Worker() { init(); XmlDocument doc = new XmlDocument(); if (File.Exists(_jobsConfPath)) { doc.Load(_jobsConfPath); XmlElement elem = doc.DocumentElement; String name, master, start; int id; //for every job foreach (XmlElement item in elem.ChildNodes) { Dictionary<String, String> clients = new Dictionary<String, String>(); HashSet<String> excl = new HashSet<string>(); HashSet<String> exclre = new HashSet<string>(); XmlElement nameNode = (XmlElement)item.GetElementsByTagName("title").Item(0); XmlElement masterNode = (XmlElement)item.GetElementsByTagName("master").Item(0); XmlElement idNode = (XmlElement)item.GetElementsByTagName("id").Item(0); XmlElement ignore = (XmlElement)item.GetElementsByTagName("ignore").Item(0); if(ignore.InnerText.Equals("1")){ _log.WriteLine("ignoring job {0}",idNode.InnerText); continue; } XmlElement startNode = (XmlElement)item.GetElementsByTagName("start").Item(0); XmlNodeList clientNodes = item.GetElementsByTagName("client"); XmlNodeList exclNodes = item.GetElementsByTagName("exclude"); XmlNodeList exclreNodes = item.GetElementsByTagName("exclude_re"); if (nameNode == null || idNode == null || masterNode == null || clientNodes.Count == 0 || startNode == null) { _log.WriteLine("WARN: job is missing essential info"); } else { name = nameNode.InnerText; id = Int32.Parse(idNode.InnerText); start = startNode.InnerText; master = masterNode.InnerText; HashSet<String> noDuplCli = new HashSet<string>(); //be sure there are no duplicates clients foreach (XmlElement cli in clientNodes) { String addr = ((XmlElement)cli.GetElementsByTagName("addr").Item(0)).InnerText; if (!noDuplCli.Contains(addr)) { clients.Add(((XmlElement)cli.GetElementsByTagName("id").Item(0)).InnerText, addr); } noDuplCli.Add(addr); } foreach (XmlElement ex in exclNodes) { excl.Add(ex.InnerText); } foreach (XmlElement ex in exclreNodes) { exclre.Add(ex.InnerText); } //_log.WriteLine("{0} {1} {2} {3} {4}", name, id, master, start, clients, excl, exclre); SyncJob sj = new SyncJob(name, id, start, master, clients, excl, exclre); _log.WriteLine(sj); //_log.Flush(); //calculate delay period for first run //if "start" time has passed today calculate the time for the following day, else calculate time for today. DateTime dt = Convert.ToDateTime(start); if (DateTime.Now.CompareTo(dt) > 0) { dt = dt.AddDays(1); } //int startDelay=(int) ((dt.Ticks - DateTime.Now.Ticks) / 10000000); TimeSpan span1 = TimeSpan.FromSeconds((double)(dt.Ticks - DateTime.Now.Ticks) / 10000000); lock (this) { //if(!_jobsMap.ContainsKey(start)) //{ // _jobsMap.Add(start, sj); //} System.Threading.TimerCallback tcb = new System.Threading.TimerCallback(StartJobOnTime); // start tcb with parameter SyncJob , duetime is span1 calculated earlier, repeat every 24hours System.Threading.Timer t = new Timer(tcb, sj, span1, TimeSpan.FromSeconds(24*60*60)); _log.WriteLine("created timer for {0}: {1} ", span1, TimeSpan.FromSeconds(24 * 60 * 60)); //test stuff //System.Threading.Timer t = new Timer(tcb, sj, TimeSpan.FromSeconds(sj.Id), TimeSpan.FromSeconds(2000)); //_log.WriteLine("created timer for {0}: {1} ", TimeSpan.FromSeconds(sj.Id), TimeSpan.FromSeconds(2000)); _timers.AddLast(t); } } }//ended iterating through job elements } else { _log.WriteLine("ERR: opening jobs_conf :{0}", _jobsConfPath); } _log.WriteLine(DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString()); }
/// <summary> /// Set the default values for all of the class data. /// </summary> private void Initialize() { // Set the timer callback method. callback = flashTimerTimeout; this._iterations = 0; // FONTS this.fldPreTextFont = base.Font; this.fldPostTextFont = base.Font; this.fldFlashFont = base.Font; // COLORS this.fldPreTextForeColor = ActiveGrid.Paintbox.PreTextColor; this.fldPostTextForeColor = ActiveGrid.Paintbox.PostTextColor; this.fldFlashForeColor = ActiveGrid.Paintbox.FlashForeColor; this.fldFlashBackColor = ActiveGrid.Paintbox.FlashBackgroundColor; this.fldFlashGradientStartColor = ActiveGrid.Paintbox.FlashGradientStartColor; this.fldFlashGradientEndColor = ActiveGrid.Paintbox.FlashGradientEndColor; this.fldFlashPreTextForeColor = ActiveGrid.Paintbox.FlashPreTextColor; this.fldFlashPostTextForeColor = ActiveGrid.Paintbox.FlashPostTextColor; // STRINGS this.fldPreText = String.Empty; this.fldPostText = String.Empty; this.fldFlashPreText = String.Empty; this.fldFlashPostText = String.Empty; this.fldFormat = DEFAULT_FORMAT_SPECIFIER; // MISCELLENEOUS this.fldVerticalAlignment = StringAlignment.Center; this.fldHorizontalAlignment = StringAlignment.Center; this.fldFlashLinearGradientMode = LinearGradientMode.Vertical; this.fldDisplayZeroValues = false; this.fldUseNegativeForeColor = false; this._state = CellState.Normal; this._style = CellStyle.Plain; }
new public MySqlDataReader ExecuteReader( CommandBehavior behavior ) { MySqlDataReader reader2; this.lastInsertedId = -1L; this.CheckState(); if( ( this.cmdText == null ) || ( this.cmdText.Trim().Length == 0 ) ) { throw new InvalidOperationException( Resources.CommandTextNotInitialized ); } string text = TrimSemicolons( this.cmdText ); this.connection.IsExecutingBuggyQuery = false; if( !this.connection.driver.Version.isAtLeast( 5, 0, 0 ) && this.connection.driver.Version.isAtLeast( 4, 1, 0 ) ) { string str2 = text; if( str2.Length > 0x11 ) { str2 = text.Substring( 0, 0x11 ); } str2 = str2.ToLower( CultureInfo.InvariantCulture ); this.connection.IsExecutingBuggyQuery = str2.StartsWith( "describe" ) || str2.StartsWith( "show table status" ); } if( ( this.statement == null ) || !this.statement.IsPrepared ) { if( this.CommandType == System.Data.CommandType.StoredProcedure ) { this.statement = new StoredProcedure( this, text ); } else { this.statement = new PreparableStatement( this, text ); } } this.statement.Resolve(); this.HandleCommandBehaviors( behavior ); this.updatedRowCount = -1L; System.Threading.Timer timer = null; try { MySqlDataReader reader = new MySqlDataReader( this, this.statement, behavior ); this.timedOut = false; this.statement.Execute(); if( this.connection.driver.Version.isAtLeast( 5, 0, 0 ) && ( this.commandTimeout > 0 ) ) { System.Threading.TimerCallback callback = new System.Threading.TimerCallback( this.TimeoutExpired ); timer = new System.Threading.Timer( callback, this, this.CommandTimeout * 0x3e8, -1 ); } reader.NextResult(); this.connection.Reader = reader; reader2 = reader; } catch( MySqlException exception ) { if( exception.Number == 0x525 ) { if( this.TimedOut ) { throw new MySqlException( Resources.Timeout ); } return null; } if( exception.IsFatal ) { this.Connection.Close(); } if( exception.Number == 0 ) { throw new MySqlException( Resources.FatalErrorDuringExecute, exception ); } throw; } finally { if( timer != null ) { timer.Dispose(); } } return reader2; }
/// <summary> /// /// </summary> /// <param name="clientApyKey"></param> //public void ThreadNotification(string clientApiKey, string clientDateFromtoSearch) { public void ThreadNotification(clientInfo oClient) { StateObjClass StateObj = new StateObjClass(); StateObj.TimerCanceled = false; StateObj.clientApiKey = oClient.clientApyKey; //clientApiKey; StateObj.searchfromDate = oClient.creationDate; //clientDateFromtoSearch; StateObj.clientId = oClient.idUser; System.Threading.TimerCallback TimerDelegate = new System.Threading.TimerCallback(listNotificationsThread); oThreadNotification = new Timer(TimerDelegate, StateObj, 0, Convert.ToInt32(ConfigurationSettings.AppSettings["timer"])); }
//protected override void SetVisibleCore(bool value) //{ // if (!_showWindow) // { // base.SetVisibleCore(false); // return; // } // base.SetVisibleCore(value); //} private void StartReadySignal() { textBox1.Text += string.Format("Starting to send EX_READY message...{0}", Environment.NewLine); _stateObj = new StateObjClass(); _stateObj.TimerCanceled = false; System.Threading.TimerCallback TimerDelegate = new System.Threading.TimerCallback(SendReadySignal); // Create a timer that calls a procedure every 2 seconds. // Note: There is no Start method; the timer starts running as soon as // the instance is created. System.Threading.Timer TimerItem = new System.Threading.Timer(TimerDelegate, _stateObj, 100, 1000); // Save a reference for Dispose. _stateObj.TimerReference = TimerItem; textBox1.Text += string.Format("Waiting for EX_OK message...{0}", Environment.NewLine); }