Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/database/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 自动倒计时调整数据库记录_C#_Database_Asp.net Mvc 3_Countdowntimer_Visual Web Developer 2010 - Fatal编程技术网

C# 自动倒计时调整数据库记录

C# 自动倒计时调整数据库记录,c#,database,asp.net-mvc-3,countdowntimer,visual-web-developer-2010,C#,Database,Asp.net Mvc 3,Countdowntimer,Visual Web Developer 2010,我有一个小的MVC网站,是为朋友们的美发沙龙。在这个页面上,我有一个div,用于显示从数据库记录中获取的数字。此数字是当前排队等待理发的人数 我目前拥有的是登录到“管理员”页面并使用表单更新此号码的能力,从“2”改为“5”,然后根据队列中的人数将“5”改为“6” 这是目前的手动操作。代码如下: ============================= 控制器 ==================================== 模型代码 { 公共类数据 { 公共int ID{get;set

我有一个小的MVC网站,是为朋友们的美发沙龙。在这个页面上,我有一个div,用于显示从数据库记录中获取的数字。此数字是当前排队等待理发的人数

我目前拥有的是登录到“管理员”页面并使用表单更新此号码的能力,从“2”改为“5”,然后根据队列中的人数将“5”改为“6”

这是目前的手动操作。代码如下:

=============================

控制器 ====================================

模型代码
{
公共类数据
{
公共int ID{get;set;}
公共字符串队列号{get;set;}
}
公共类DataDBContext:DbContext
{
公共DbSetQueue{get;set;}
}
}
我真正希望发生的是,一旦您手动更新了“管理”页面上表单中的队列号,我希望自动倒计时20分钟(理发所需的大致时间),然后让队列号自动向下调整1,直到达到“0”

e、 g.我们有5人排队,20分钟后自动调整为4人,网页将自动更新/刷新,然后又有2人进入,因此我们手动将其调整为6人排队,计时器再次启动,每过20分钟,队列将调整-1,直到降到“0”。一旦到达“0”,它将一直停留在那里,直到我们手动将更多的人添加到队列中

恐怕我甚至不知道如何开始这样一个请求,或者即使它是可能的


我真的很感谢这里的专家们的帮助,他们可能会帮我“婴儿步”。任何我没有提供的信息,我都会尽力补充——我意识到我并不擅长解释自己:-(

您考虑过Ajax吗?您是否将上次更新的时间存储在手动设置标志上?您可以使用Ajax请求,使用jquery Set interval同时运行。这将每2分钟触发一次Ajax请求。查找上次更新的时间,如果超过20分钟,则从数据库中删除一次,您的返回将是新号码和jquery可以为您更新该号码

实际上,这是一个相当简单的过程,但需要更多关于底层数据的细节

从你的问题来看,我是如何看待它的

在控制器中

public ActionResult ajaxUpdate()
        {
            //open connection
            dbcontext db = new dbcontext();
            db.Connection.Open();

            // get the last updated record in the database.
            var entry = db.Entry.OrderByDecending(m=> m.LastUpdatedDate).FirstOrDefault();

            //clean up
            db.Connection.Close();
            db.Dispose();

            //return -1 as error
            if(entry == null){

                return Json(-1,JsonRequestBehavior.AllowGet);

            }

            // get current number of people in queue
            Int32 numberOfPeople = entry.QueueNumber;

            TimeSpan span = DateTime.Now.Subtract(entry.LastUpdatedDate);

            if(span.Minutes >= 20){

                // if 20 mins have passed assume a person has been completed since manual update
                numberOfPeople--;

            }

            //this returns a number, alternatively you can return a Partial
            return Json(numberOfPeople, JsonRequestBehavior.AllowGet);
        }
Jquery和Ajax

$(document).ready(function () {

    // run function every x minutes
    setInterval(function () {
        UpdateQueue();
    }, 100000);





});
    function UpdateQueue() {

    $.ajax({
        cache: true,
        type: 'POST',
        url: "/ControllerName/ajaxUpdate",
        async: false,
        dataType: "json",
        success: function (result) {
            // on success result will be the number returned

            // -1 is error
            if (result == -1) {
                return;

            }

            // check the -- didn't return a negative
            if (result < 0) {

                result = 0;

            }

            //find your element in the HTML to update
            $('#NumberElement').text().replaceWith(result);


        }

    });


}
$(文档).ready(函数(){
//每x分钟运行一次函数
setInterval(函数(){
UpdateQueue();
}, 100000);
});
函数UpdateQueue(){
$.ajax({
是的,
键入:“POST”,
url:“/ControllerName/ajaxUpdate”,
async:false,
数据类型:“json”,
成功:功能(结果){
//成功时,结果将是返回的数字
//-1是错误
如果(结果==-1){
返回;
}
//检查——没有返回负数
如果(结果<0){
结果=0;
}
//在HTML中查找要更新的元素
$('#numberrelation').text().replaceWith(结果);
}
});
}

您必须确保在包含此代码之前包含jquery库,否则将无法定义jquery。

我已经用一点线程技术为您弥补了服务器端解决方案。希望我在关键部分的描述是正确的

它的一个优点是,应用程序的管理员不必挂在页面上就可以统计当前客户的数量(就像他在ajax请求中应该做的那样)

它的工作原理

在“number of customers”(客户数)更新中,它正在启动(如有必要)新的倒计时线程,该线程将等待(休眠)预定义的时间间隔,然后减少数量

public class CustomerAdminService
{
    // time in milliseconds it will take to decrease number of waiting customers 
    const int sleepTime = 10000;
    // current number of customers (just for simplicity - you can have it in db or somewhere else)
    static int numberOfCustomers;

    static Thread updaterThread;

    // object lock
    static readonly object locker = new Object();

    public int GetNumberOfCustomers()
    {
        return numberOfCustomers;
    }

    public void UpdateCustomers(int value)
    {
        lock (locker)
        {
            if (updaterThread == null)
            {
                //start new downcounting thread
                updaterThread = new Thread(new ThreadStart(UpdateWorker));
                updaterThread.Start();
            }
            SetNumberOfWaitingCustomers(value);
        }
    }

    private void SetNumberOfWaitingCustomers(int value)
    {
        numberOfCustomers = value;
    }

    // downcounting thread method
    private void UpdateWorker()
    {      
        while (true)
        {
            // sleep for predefined time
            Thread.Sleep(sleepTime);
            lock (locker)
            {              
                var number = GetNumberOfCustomers();             
                if (number <= 1)
                {
                    // if number of currents customers is now zero - end the downcounting thread
                    SetNumberOfWaitingCustomers(0);
                    updaterThread = null;
                    return;
                }
                SetNumberOfWaitingCustomers(number - 1);
            }
        }
    }
}
公共类CustomerAdminService
{
//减少等待的客户数量所需的时间(毫秒)
const int sleepTime=10000;
//当前的客户数量(为了简单起见,您可以在db或其他地方使用)
静态客户数;
静态线程更新线程;
//对象锁
静态只读对象锁定器=新对象();
public int GetNumberOfCustomers()
{
返回客户数量;
}
public void UpdateCustomers(int值)
{
锁(储物柜)
{
if(updaterThread==null)
{
//启动新的倒计时线程
updaterThread=新线程(新线程开始(UpdateWorker));
updaterThread.Start();
}
SetNumberOfWaitingCustomers(值);
}
}
私有void SetNumberOfWaitingCustomers(int值)
{
顾客数量=价值;
}
//倒计时线程法
私有void UpdateWorker()
{      
while(true)
{
//按预定时间睡觉
睡眠(睡眠时间);
锁(储物柜)
{              
var number=GetNumberOfCustomers();

如果(数字是的Ajax是关键。您的网站可以使用它在不明显的情况下与服务器通信。

另一种方法是不更新数据库中的计数,而只是使用查询来确定特定时间段内的客户数。您可以通过修改模型而不是
排队来实现这一点umber
它使用到达时间并更改控制器,以便插入新的数据记录

{
    public class Data
    {
        public int ID { get; set; }
        public DateTime Arrival_Time { get; set; }
    }

    public class DataDBContext : DbContext
    {
        public DbSet<Data> Queue { get; set; }
    } 
}

这种方法的好处是,如果理发开始需要更长的时间(比如30分钟),您只需更改查询,应用程序就可以继续工作。

谢谢Craig,我没有考虑Ajax,主要是因为我刚刚开始使用MVC,没有编码背景
public class CustomerAdminService
{
    // time in milliseconds it will take to decrease number of waiting customers 
    const int sleepTime = 10000;
    // current number of customers (just for simplicity - you can have it in db or somewhere else)
    static int numberOfCustomers;

    static Thread updaterThread;

    // object lock
    static readonly object locker = new Object();

    public int GetNumberOfCustomers()
    {
        return numberOfCustomers;
    }

    public void UpdateCustomers(int value)
    {
        lock (locker)
        {
            if (updaterThread == null)
            {
                //start new downcounting thread
                updaterThread = new Thread(new ThreadStart(UpdateWorker));
                updaterThread.Start();
            }
            SetNumberOfWaitingCustomers(value);
        }
    }

    private void SetNumberOfWaitingCustomers(int value)
    {
        numberOfCustomers = value;
    }

    // downcounting thread method
    private void UpdateWorker()
    {      
        while (true)
        {
            // sleep for predefined time
            Thread.Sleep(sleepTime);
            lock (locker)
            {              
                var number = GetNumberOfCustomers();             
                if (number <= 1)
                {
                    // if number of currents customers is now zero - end the downcounting thread
                    SetNumberOfWaitingCustomers(0);
                    updaterThread = null;
                    return;
                }
                SetNumberOfWaitingCustomers(number - 1);
            }
        }
    }
}
{
    public class Data
    {
        public int ID { get; set; }
        public DateTime Arrival_Time { get; set; }
    }

    public class DataDBContext : DbContext
    {
        public DbSet<Data> Queue { get; set; }
    } 
}
[HttpGet]
public ActionResult NumberOfPeopleInQueue()
{
    var result = db.NumberOfCustomersSince(DateTime.Now.AddMinutes(-20));
    return Json(result);
}