BanProductByTimeService.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Linq;
  5. using System.Threading;
  6. using MySystem.Models;
  7. using Library;
  8. namespace MySystem
  9. {
  10. /// <summary>
  11. /// 定时下架商品
  12. /// </summary>
  13. public class BanProductByTimeService
  14. {
  15. public readonly static BanProductByTimeService Instance = new BanProductByTimeService();
  16. private BanProductByTimeService()
  17. { }
  18. public void Start()
  19. {
  20. Thread th = new Thread(doSomething);
  21. th.IsBackground = true;
  22. th.Start();
  23. }
  24. public void doSomething()
  25. {
  26. while (true)
  27. {
  28. try
  29. {
  30. WebCMSEntities db = new WebCMSEntities();
  31. var check = db.Products.Any(m => m.Status == 1 && m.EndDate <= DateTime.Now);
  32. if (check)
  33. {
  34. var lists = db.Products.Where(m => m.Status == 1 && m.EndDate <= DateTime.Now).ToList();
  35. foreach (var item in lists)
  36. {
  37. var list = lists.FirstOrDefault(m => m.Id == item.Id);
  38. list.Status = 0;
  39. list.EndDate = null;
  40. list.UpdateMan = "商品自动下架";
  41. }
  42. db.SaveChanges();
  43. }
  44. }
  45. catch (Exception ex)
  46. {
  47. function.WriteLog(DateTime.Now.ToString() + ":" + ex.ToString(), "商品自动下架异常");
  48. }
  49. Thread.Sleep(1000);
  50. }
  51. }
  52. }
  53. }