我正在尝试定期调用一个函数。
下面的代码写在global.asax.cs文件,它的工作是 ScheduleTaskTrigger()电话 CheckLicenseExpiry() 1 分钟 后。但我也想每隔 调用一次此函数,比方说 4 小时。
是否可以通过更改此代码来实现此目的:
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
//used here formating API//
HttpConfiguration config = GlobalConfiguration.Configuration;
config.Formatters.JsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
ScheduleTaskTrigger();
}
static void ScheduleTaskTrigger()
{
HttpRuntime.Cache.Add("ScheduledTaskTrigger",
string.Empty,
null,
Cache.NoAbsoluteExpiration,
// TimeSpan.FromMinutes(60), // Every 1 hour
// TimeSpan.FromMinutes(0.0167),
TimeSpan.FromMinutes(1),
CacheItemPriority.NotRemovable,
new CacheItemRemovedCallback(CheckLicenseExpiry));
}
static void CheckLicenseExpiry(string key, Object value, CacheItemRemovedReason reason)
{
CompanyHelper.CheckLicenseExpired();
}
请您参考如下方法:
如果您愿意使用 Windows 窗体,请使用“Timer”类。
using System.Windows.Forms;
//[...]
Timer timer;
private void Initialiser()
{
Timer timer = new Timer();
timer.Interval = 3600000;//Set interval to an hour in the form of milliseconds.
timer.Tick += new EventHandler(timer_Tick);
}
private void timer_Tick(object sender, EventArgs e)
{
//The function you wish to do every hour.
}
您可以将间隔更改为任何形式,只要它是毫秒形式(每秒 1000 次)。 (例如 1 分钟:60000,4 小时:14400000)。
P.S 您可以只使用“System.Windows.Forms”库而不必使用 Windows 窗体程序,我想您也可以在 WPF 中使用此代码。
