First, tools:
Vs2015+net Framework4.5.
Second, Operation:
1, Timer settings:
2. Log code:
Third, the code:
1. Log Code:
1///<summary>2///Logging of windowns Services3///</summary>4///<param name= "DbLog" ></param>5PublicStaticvoid Writedblogfile (StringDBLOG)6{7//string logfilename = HttpContext.Current.Server.MapPath ("/log") + "/log_" + DateTime.Now.ToString ("yyyy-mm-dd") + ". txt ";8String LogFileName = AppDomain.CurrentDomain.BaseDirectory +"/log_"+ DateTime.Now.ToString ("Yyyy-mm-dd") +". txt";9System.IO.StreamWriter write;Ten write =New System.IO.StreamWriter (LogFileName,True, System.Text.Encoding.Default);Write one by one. Basestream.seek (0, System.IO.SeekOrigin.End);Write. AutoFlush =True;13if (Null! =Write14{15Lock(write)16{17//Write. WriteLine ("—————————————— windowns service logging started ————————————————");Write. WriteLine ("Log contents of the Windowns service:" + DbLog); 19 write. WriteLine ( "windowns service: "+ DateTime.Now); 20 //write. WriteLine ("———————————————— logging end of the —————————————— windowns Service"); 21 write. Flush (); 22 }23 }24 write. Close (); 25 write = null;26}
2. Timer Setup code:
1UsingCommon;2UsingSystem;3UsingSystem.Collections.Generic;4UsingSystem.ComponentModel;5UsingSystem.Data;6UsingSystem.Diagnostics;7UsingSystem.Linq;8UsingSystem.ServiceProcess;9UsingSystem.Text;10UsingSystem.Threading;11UsingSystem.Threading.Tasks;1213NamespaceWindowsservicedb14{15PublicPartialClassService1:servicebase16{17System.Timers.Timer Timer;//Timer19PublicService1 ()20{21stInitializeComponent ();22}2324ProtectedOverridevoid OnStart (String[] args)25{Thread thread =New Thread (Delegate()27{28Try29{30for (int i =0; I <10; i++)31{32//Utils.writedblogfile ("—————————————— windowns service logging started ————————————————");33Timer =NewSystem.Timers.Timer ();a timer. Interval =3000;a timer. Elapsed + =NewSystem.Timers.ElapsedEventHandler (timer_elapsed);Notoginseng timer. AutoReset =True//Whether the setting is executed once (false) or always executed (true);a timer. Enabled =True//Whether to execute the System.Timers.Timer.Elapsed event;Utils.writedblogfile ("Service Start time:" +DateTime.Now);40}41}42Catch(Exception ex)43{44Utils.writedblogfile ("Service failed to start" +ex);46}47});48//Utils.writedblogfile ("———————————————— logging end of the —————————————— windowns Service");The thread. Name ="Threading Test 1";The thread. IsBackground =True;51Thread. Start ();52}5354ProtectedOverridevoidOnStop ()55{The timer. Enabled =False;Utils.writedblogfile ("End of service time:" +DateTime.Now);58}59 60 private void timer_elapsed (object sender, System.Timers.ElapsedEventArgs e) 61 {62 // perform operation 63 Utils.writedblogfile ( " service start record Time: "+ DateTime.Now); 64 65 }66 }67}
Iv. Summary:
"C#windows Service" "Three" timer settings