如何在C#中设置计时器?

Sha*_*zal 2 c# timer

我正在用C#编写一个程序,每15分钟就会ping一次"google".如果ping成功,它将在15分钟后再次检查(ping)等等......如果ping不成功,它将执行我的ISP的dailer并在每15分钟后再次检查.

我已经编写了所有代码,但我似乎无法设置计时器每15分钟后重复一次代码.如果有人可以帮助我,我会非常感激.

这是代码.

using System;
using System.Windows.Forms;
using System.Net.NetworkInformation;
using System.Net;
using System.Diagnostics;

namespace WindowsFormsApplication4
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        timer.Interval = (4000); //For checking, I have set the interval to 4 sec. It actually needs to be 15 minutes.
        timer.Enabled = true; 
        timer.Start(); 

        Ping ping = new Ping();

        PingReply pingStatus = ping.Send(IPAddress.Parse("208.69.34.231"));

        if (pingStatus.Status != IPStatus.Success)
        {
            timer.Tick += new EventHandler(timer1_Tick);
        }

    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        Process.Start("C:\\WINDOWS\\system32\\rasphone.exe","-d DELTA1");
    }

}
}
Run Code Online (Sandbox Code Playgroud)

这段代码的作用是,如果我执行此程序时拨号器已连接 - 它什么都不做.4秒后甚至没有重新检查.但是如果在我运行此程序时没有连接拨号器,它会立即连接我的拨号器并尝试在每4秒后重新连接拨号器,甚至不检查(ping谷歌).

我似乎无法正确设置计时器,因为我之前从未使用过计时器功能.如果有人可以帮助我,我真的很感激.

此致,Shajee A.

p.s*_*w.g 14

听起来你只需要在你的计时器Tick处理程序中移动你的ping代码.像这样:

private void Form1_Load(object sender, EventArgs e)
{
    timer.Interval = 4000;
    timer.Enabled = true; 
    timer.Tick += new EventHandler(timer1_Tick);
    timer.Start(); 
}

private void timer1_Tick(object sender, EventArgs e)
{
    Ping ping = new Ping();
    PingReply pingStatus = ping.Send(IPAddress.Parse("208.69.34.231"));

    if (pingStatus.Status != IPStatus.Success)
    {
        Process.Start("C:\\WINDOWS\\system32\\rasphone.exe","-d DELTA1");
    }
}
Run Code Online (Sandbox Code Playgroud)