dayUsers.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. 'use strict';
  2. const Subscription = require('egg').Subscription;
  3. // 2023/8/25 每日统计登录人数
  4. class dayUsers extends Subscription {
  5. /**
  6. * cron
  7. * * * * * * *
  8. * ┬ ┬ ┬ ┬ ┬ ┬
  9. * │ │ │ │ │ |
  10. * │ │ │ │ │ └ day of week (0 - 7) (0 or 7 is Sun)
  11. * │ │ │ │ └───── month (1 - 12)
  12. * │ │ │ └────────── day of month (1 - 31)
  13. * │ │ └─────────────── hour (0 - 23)
  14. * │ └──────────────────── minute (0 - 59)
  15. * └───────────────────────── second (0 - 59, optional)
  16. * @returns {{cron: string, type: string}}
  17. */
  18. // 通过 schedule 属性来设置定时任务的执行间隔等配置
  19. static get schedule() {
  20. return {
  21. // interval: '1m', // 1 分钟间隔
  22. // interval: '10s', // 10s
  23. // cron: '0 0 */3 * * *', // 每三小时准点执行一次
  24. cron: '0 58 23 * * *', // 每天23:58执行一次
  25. type: 'all', // 指定所有的 worker 都需要执行
  26. };
  27. }
  28. // subscribe 是真正定时任务执行时被运行的函数
  29. async subscribe() {
  30. const that = this;
  31. const seq = that.app.Sequelize;
  32. const tmpTime = that.app.szjcomo.time();
  33. const transaction = await that.app.model.transaction();
  34. try {
  35. const users = await that.app.model.Users.findAll({
  36. where: { update_ttime: { [seq.Op.between]: [ `${that.app.szjcomo.date('Y-m-d', tmpTime)} 00:00:00`, `${that.app.szjcomo.date('Y-m-d', tmpTime)} 23:59:59` ] } },
  37. order: [[ 'update_ttime', 'asc' ]],
  38. attributes: [ 'user_id', 'nickname', 'headimgurl', 'login_time', 'update_ttime', 'is_employee' ],
  39. });
  40. const result = JSON.parse(JSON.stringify(users));
  41. // 2023/8/27 批量创建用户登录记录
  42. const datas = await result.map(item => {
  43. return Object.assign(item, {
  44. create_time: that.app.szjcomo.date('Y-m-d H:i:s'),
  45. });
  46. });
  47. await that.app.model.UserLoginLogs.bulkCreate(datas, { transaction });
  48. transaction.commit();
  49. } catch (e) {
  50. console.log(e);
  51. if (transaction) {
  52. transaction.rollback();
  53. }
  54. }
  55. }
  56. }
  57. module.exports = dayUsers;