Sabtu, 06 Oktober 2012

Funsi Timer pada C#


Timer in C#


The Timer control allows you to set a time interval to execute an event after that interval continuously. It is useful when you want to execute certain applications after a certain interval. Say you want to create a backup of your data processing in every hour. You can make a routine which will take the backup and call that routine on Timer's event and set timer interval for an hour.
Using timer control is very simple. To test the control, I'm going to create a Windows Application. I also add two button controls to the form and change their text to Start and Stop as you can see from the following Figure.


In this application, I'm going to create a text file mcb.txt in your C:\temp directory and start writing the time after 5 seconds interval. Stop button stops the timer and Start again start the timer.
Note: If you do not have a temp folder on your C:\ Drive, you must change this path.
Now you can drag a timer control from the toolbox to the form from Toolbox of Visual Studio. You can set timer properties from the IDE as well as programmatically. To set the timer properties, right click on the timer control and change Interval property. As you can see from the Figure,

I put 5000 milliseconds (5 seconds). 

1 sec = 1000 milliseconds.

Now click on the Events button and write event for the timer click as you can see from the following figure.


Now I add a FileStream and a StreamWriter object in the beginning of the class. As you can see from the following code, FileStream class creates a mcb.txt file and StreamWriter will be used to write to the file.

private static FileStream fs = new
 FileStream(@"c:\temp\mcb.txt", FileMode.OpenOrCreate, FileAccess.Write);private static StreamWriter m_streamWriter = new StreamWriter(fs);

Now write the following code on the Form Load event:

private void Form1_Load(object sender, System.EventArgs e)
{
// Write to the file using StreamWriter classm_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
m_streamWriter.Write(" File Write Operation Starts : ");
m_streamWriter.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(),DateTime.Now.ToLongDateString());
m_streamWriter.WriteLine(" ===================================== \n");
m_streamWriter.Flush();
}
As you can see from the above code, this code writes some lines to the file.
Now write code on the start and stop button click handlers. As you can see from the following code, the Start button click sets timer's Enabled property as true. Setting timer's Enabled property starts timer to execute the timer event. I set Enabled property as false on the Stop button click event handler, which stops executing the timer tick event.
private void button1_Click(object sender, System.EventArgs e)
{
timer1.Enabled = 
true
;
}
private void button2_Click(object
 sender, System.EventArgs e)
{
timer1.Enabled = 
false
;
}

Now last step 
is
 to write timer's tick event to write current time to the text file. Write the following code on your timer event.
private void timer1_Tick(object
 sender, System.EventArgs e)
{
m_streamWriter.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(),DateTime.Now.ToLongDateString());
m_streamWriter.Flush();
}
Now use Start and Stop buttons to start and stop the timer. The output mcb.txt file looks like the following figure.


Using Timer control Programmatically
If you don't have Visual Studio .NET, you can also write the same sample. Just following these steps.
Creating an instance of Timer
The Timer class's constructor is used to create a timer object. The constructor is overloaded.
Public Timer()
Public Timer(
double
) Sets the interval property to the specified.

Here is
 how to create a Timer with 5 seconds interval.

Timer myTimer = 
new
 Timer(500);
Here are some useful members of the Timer class:
TickThis event occurs when the Interval has elapsed. 
StartStarts raising the Tick event by setting Enabled to true. 
StopStops raising the Tick event by setting Enabled to false. 
CloseReleases the resources used by the Timer. 
AutoResetIndicates whether the Timer raises the Tick event each time the specified Interval has elapsed or whether the Tick event is raised only once after the first interval has elapsed.
IntervalIndicates the interval on which to raise the Tick event.
EnabledIndicates whether the Timer raises the Tick event.
How to use Timer class to raise an event after certain interval?
timer1.Interval = 5000;
timer1.Enabled = 
true
;
timer1.Tick += 
new
 System.EventHandler (OnTimerEvent);Write the event handler
This event will be executed after every 5 secs.

public static void OnTimerEvent(object
 source, EventArgs e)
{
m_streamWriter.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(),DateTime.Now.ToLongDateString());
m_streamWriter.Flush();
}
You use Stop and Close events to stop the timer and release the resources. See attached project for more details




Menggunakan Timer dalam Program

Menggunakan timer dalam program csharp
Timer adalah salah satu komponen dalam pemrograman yang sering kita pakai. Komponen timer ini biasa kita gunakan untuk menjalankan proses secara rutin pada saat-saat tertentu. Proses itu bisa hanya sekali dijalankan atau diulang per-satuan waktu sesuai dengan interval waktu yang ditentukan dalam komponen timer ini. Kita akan mempelajarinya dengan contoh.

Kita akan membuat sebuah program yang berisi 9 buah komponen label, satu buah tombol, dan satu buah komponen timer. Setiap Label akan berubah warnanya setiap 100ms.

Pada saat tombol mulai diklik, warna label akan berubah bergantian dari label pertama sampai label ke-9. Perubahan warna ini dikontrol dengan menggunakan komponen timer yang kita set interval waktunya adalah 100ms. Gambaran dari program ini adalah seperti yang terlihat pada gambar berikut ini:

Menggunakan timer dalam program csharp


Rutin implementasi nya adalah seperti yang tertulis dibawah ini.
  1. using System;  
  2. using System.Windows.Forms;  
  3.   
  4. public class MyTimer : Form  
  5. {  
  6.   private System.Windows.Forms.Label label1;  
  7.   private System.Windows.Forms.Label label2;  
  8.   private System.Windows.Forms.Label label3;  
  9.   private System.Windows.Forms.Label label4;  
  10.   private System.Windows.Forms.Label label5;  
  11.   private System.Windows.Forms.Label label6;  
  12.   private System.Windows.Forms.Label label7;  
  13.   private System.Windows.Forms.Label label8;  
  14.   private System.Windows.Forms.Label label9;  
  15.   private System.Windows.Forms.Button btnStart;  
  16.   private System.Windows.Forms.Timer timer1;  
  17.   private int index;    
  18.   private System.ComponentModel.IContainer components = null;  
  19.   
  20.   public MyTimer()  
  21.   {  
  22.     components = new System.ComponentModel.Container();  
  23.     label1 = new System.Windows.Forms.Label();  
  24.     label2 = new System.Windows.Forms.Label();  
  25.     label3 = new System.Windows.Forms.Label();  
  26.     label4 = new System.Windows.Forms.Label();  
  27.     label5 = new System.Windows.Forms.Label();  
  28.     label6 = new System.Windows.Forms.Label();  
  29.     label7 = new System.Windows.Forms.Label();  
  30.     label8 = new System.Windows.Forms.Label();  
  31.     label9 = new System.Windows.Forms.Label();  
  32.     btnStart = new System.Windows.Forms.Button();  
  33.     timer1 = new System.Windows.Forms.Timer(components);  
  34.     //   
  35.     // label1  
  36.     //   
  37.     label1.BackColor = System.Drawing.Color.Lime;  
  38.     label1.Location = new System.Drawing.Point(20, 30);  
  39.     label1.Size = new System.Drawing.Size(61, 34);  
  40.     label1.Text = "1";  
  41.     label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;  
  42.     //   
  43.     // label2  
  44.     //   
  45.     label2.BackColor = System.Drawing.Color.White;  
  46.     label2.Location = new System.Drawing.Point(87, 30);  
  47.     label2.Size = new System.Drawing.Size(61, 34);  
  48.     label2.Text = "2";  
  49.     label2.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;  
  50.     //   
  51.     // label3  
  52.     //   
  53.     label3.BackColor = System.Drawing.Color.White;  
  54.     label3.Location = new System.Drawing.Point(154, 30);  
  55.     label3.Size = new System.Drawing.Size(61, 34);  
  56.     label3.Text = "3";  
  57.     label3.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;  
  58.     //   
  59.     // label4  
  60.     //   
  61.     label4.BackColor = System.Drawing.Color.White;  
  62.     label4.Location = new System.Drawing.Point(20, 74);  
  63.     label4.Size = new System.Drawing.Size(61, 34);  
  64.     label4.Text = "4";  
  65.     label4.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;  
  66.     //   
  67.     // label5  
  68.     //   
  69.     label5.BackColor = System.Drawing.Color.White;  
  70.     label5.Location = new System.Drawing.Point(87, 74);  
  71.     label5.Size = new System.Drawing.Size(61, 34);  
  72.     label5.Text = "5";  
  73.     label5.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;  
  74.     //   
  75.     // label6  
  76.     //   
  77.     label6.BackColor = System.Drawing.Color.White;  
  78.     label6.Location = new System.Drawing.Point(154, 74);  
  79.     label6.Size = new System.Drawing.Size(61, 34);  
  80.     label6.Text = "6";  
  81.     label6.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;  
  82.     //   
  83.     // label7  
  84.     //   
  85.     label7.BackColor = System.Drawing.Color.White;  
  86.     label7.Location = new System.Drawing.Point(20, 118);  
  87.     label7.Size = new System.Drawing.Size(61, 34);  
  88.     label7.Text = "7";  
  89.     label7.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;  
  90.     //   
  91.     // label8  
  92.     //   
  93.     label8.BackColor = System.Drawing.Color.White;  
  94.     label8.Location = new System.Drawing.Point(87, 118);  
  95.     label8.Size = new System.Drawing.Size(61, 34);  
  96.     label8.Text = "8";  
  97.     label8.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;  
  98.     //   
  99.     // label9  
  100.     //   
  101.     label9.BackColor = System.Drawing.Color.White;  
  102.     label9.Location = new System.Drawing.Point(154, 118);  
  103.     label9.Size = new System.Drawing.Size(61, 34);  
  104.     label9.Text = "9";  
  105.     label9.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;  
  106.     //   
  107.     // btnStart  
  108.     //   
  109.     btnStart.Location = new System.Drawing.Point(140, 167);  
  110.     btnStart.Size = new System.Drawing.Size(75, 23);  
  111.     btnStart.Text = "Mulai";  
  112.     btnStart.Click += new System.EventHandler(btnStart_Click);  
  113.     //   
  114.     // timer1  
  115.     //   
  116.     timer1.Interval = 1000;  
  117.     timer1.Tick += new System.EventHandler(timer1_Tick);  
  118.     //   
  119.     // Form6  
  120.     //   
  121.     Size = new System.Drawing.Size(480, 230);  
  122.     Controls.Add(btnStart);  
  123.     Controls.Add(label9);  
  124.     Controls.Add(label5);  
  125.     Controls.Add(label3);  
  126.     Controls.Add(label8);  
  127.     Controls.Add(label7);  
  128.     Controls.Add(label6);  
  129.     Controls.Add(label4);  
  130.     Controls.Add(label2);  
  131.     Controls.Add(label1);  
  132.     Text = "Demo Pemakaian Timer (http://abcsharpind.blogspot.com)";  
  133.     index = 0;  
  134.   }  
  135.   
  136.   private void btnStart_Click(object sender, EventArgs e)  
  137.   {  
  138.       timer1.Enabled = !timer1.Enabled;  
  139.       if (timer1.Enabled)  
  140.       {  
  141.           btnStart.Text = "Selesi";  
  142.       }  
  143.       else  
  144.       {  
  145.           btnStart.Text = "Mulai";  
  146.       }  
  147.   
  148.   }  
  149.   
  150.   private void timer1_Tick(object sender, EventArgs e)  
  151.   {  
  152.       index = (index + 1) % 9;  
  153.       switch (index)  
  154.       {  
  155.           case 0:  
  156.               label9.BackColor = System.Drawing.Color.White;  
  157.               label1.BackColor = System.Drawing.Color.Lime;  
  158.               break;  
  159.           case 1:  
  160.               label1.BackColor = System.Drawing.Color.White;  
  161.               label2.BackColor = System.Drawing.Color.Lime;  
  162.               break;  
  163.           case 2:  
  164.               label2.BackColor = System.Drawing.Color.White;  
  165.               label3.BackColor = System.Drawing.Color.Lime;  
  166.               break;  
  167.           case 3:  
  168.               label3.BackColor = System.Drawing.Color.White;  
  169.               label4.BackColor = System.Drawing.Color.Lime;  
  170.               break;  
  171.           case 4:  
  172.               label4.BackColor = System.Drawing.Color.White;  
  173.               label5.BackColor = System.Drawing.Color.Lime;  
  174.               break;  
  175.           case 5:  
  176.               label5.BackColor = System.Drawing.Color.White;  
  177.               label6.BackColor = System.Drawing.Color.Lime;  
  178.               break;  
  179.           case 6:  
  180.               label6.BackColor = System.Drawing.Color.White;  
  181.               label7.BackColor = System.Drawing.Color.Lime;  
  182.               break;  
  183.           case 7:  
  184.               label7.BackColor = System.Drawing.Color.White;  
  185.               label8.BackColor = System.Drawing.Color.Lime;  
  186.               break;  
  187.           case 8:  
  188.               label8.BackColor = System.Drawing.Color.White;  
  189.               label9.BackColor = System.Drawing.Color.Lime;  
  190.               break;  
  191.       }  
  192.   }  
  193.   
  194.   public static void Main()  
  195.   {  
  196.      Application.EnableVisualStyles();  
  197.      Application.SetCompatibleTextRenderingDefault(false);  
  198.      MyTimer p ;  
  199.      p = new MyTimer();  
  200.      Application.Run(p);          
  201.   }  
  202.     
  203. }  


0 Comments:

Posting Komentar