Asp.net web api 如何在WebAPI中每5分钟发送一次数据
我有一个项目WebAPI,我想每隔5分钟左右向客户提供数据:Asp.net web api 如何在WebAPI中每5分钟发送一次数据,asp.net-web-api,Asp.net Web Api,我有一个项目WebAPI,我想每隔5分钟左右向客户提供数据: using System; using System.Web.Http; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace MyWebApi.Controllers { public class EventController : ApiController { public string Get()
using System;
using System.Web.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace MyWebApi.Controllers
{
public class EventController : ApiController
{
public string Get()
{
var id = Guid.NewGuid();
string result = JsonConvert.SerializeObject(id, new IsoDateTimeConverter());
return result;
}
}
}
你为什么不使用定时器呢。您可以创建静态对象,并将时间间隔设置为5分钟。
这是我从中得到的一个例子
公共静态类TimerExample
{
静态定时器;
静态列表;
公共静态列表日期列表
{
得到
{
如果(_l==null)
{
Start();//启动计时器
}
返回;
}
}
静态void Start()
{
_l=新列表();
_定时器=新定时器(300000);//将定时器设置为5分钟
_timer.appeased+=新的ElapsedEventHandler(_timer_appeased);
_timer.Enabled=true;
}
静态无效时间已过(对象发送器,ElapsedEventArgs e)
{
//在此处添加事件
}
}
那么错误或问题是什么呢!WebAPI每5分钟发送一次数据的方式您到目前为止已经尝试过了!!你的问题没有显示出你对问题的任何研究成果。若要将数据从WebAPI发送到客户端,请参阅HTTP is请求/响应之类的内容。您需要使用轮询或WebSocket之类的工具+信号机上的1,在可用时使用WebSocket,如果WebSocket不可用,则具有。
public static class TimerExample
{
static Timer _timer;
static List<DateTime> _l;
public static List<DateTime> DateList
{
get
{
if (_l == null)
{
Start(); // Start the timer
}
return _l;
}
}
static void Start()
{
_l = new List<DateTime>();
_timer = new Timer(300000); // Set up the timer for 5 mins
_timer.Elapsed += new ElapsedEventHandler(_timer_Elapsed);
_timer.Enabled = true;
}
static void _timer_Elapsed(object sender, ElapsedEventArgs e)
{
// Add event here
}
}