How to calculate the total time a user spending on an application?

后端 未结 6 1039
Happy的楠姐
Happy的楠姐 2021-02-07 08:16

I want to create an application that able to calculate the total time the user (i.e. myself) spent on a particular application, for example Firefox. And this application should

相关标签:
6条回答
  • 2021-02-07 08:30

    I highly recommend signing up for RescueTime

    The simple reasons is:

    1. It does want you've asked. (Tracking application use, browser use, differentiates between productive and unproductive web browsing, alerts you if you spend too much time slacking off, etc.)
    2. It's incredibly fast to set up (so you aren't wasting even more time).
    3. It's free (for all the things you need it for).

    I wrote a blog post about how useful this tool was once. I'll summarize it here.


    This is a program you install on your computer that tracks what program has focus throughout the day, and then some. Every application’s usage time is measured, and when using a browser, the time you spend on individual websites is measured as well. With a control panel that lets you categorize every program and specific websites (and group together others), and lets you determine whether that program or website is associated with productive work, or distracting work (or neutral). By default, it knows various websites and programs like Facebook and MSN are distracting, and others like Microsoft Word and Research sites are productive – but you’re free to configure all of that:

    site classification

    As you can see above, I’ve got social networking sites, messengers, and personal email sites listed as distracting or very distracting from my work, and programs and sites that I use for work are listed as productive. There are several websites separated out from browsing, but all other websites visited are grouped under “Firefox” which is mostly the time I spend doing online research for different programming languages and paradigms.

    The program takes all of this information gathered about your time spent using your computer, and then gives you an overview of how you are spending your time throughout the day:

    dashboard

    These show that I spend up to 15 minutes every couple of hours doing something other than work. When I’m working, you can see I spent 3 hours doing research online, about 2.5 doing software development, 45 minutes with business email, etc.

    When took a break and decided to be unproductive, I spent the most time on FFYa (25 mins).

    This tool will be great for reflecting on how much work you did in a given hour, day, week, or month. Different time scales let you compare and visualize times when you’re in a crunch, vs times where you’re getting in the habit of slacking off. What’s even better, is it lets you set goals for yourself.

    Goals

    Decide for yourself how much of your day you’re willing to spend slacking off, and how much work you want to get done, and even program a pop up notification that will tell you if you’re going astray in any number of predetermined ways.

    Alerts

    One of my favourite parts, is the “AFK” detector. If you go off for lunch, or get a phone call, or go to a meeting, or fall asleep at your desk, the program will detect that you’ve been idle and give you a dialogue when you return to categorize what you were doing while you were away. This is completely customizable as well, so it will sort out whether your time away from the computer was productive or a distraction.

    enter image description here enter image description here

    Don’t trust yourself to keep on the job? It comes with a “Focus Time” feature. Here, you can tell the program how long you want to buckle down and work and during that time, it will block you from using sites and applications you’ve listed as distracting. If you really don’t trust yourself, you can make it so that you can’t unblock them until your time is up.

    focus

    I’ve only had it for a day, so I look forward to seeing how my productivity compares day to day and week to week. Since it was my first day with it, I was buckled down pretty hard, because I was self conscious about what I was doing, but I’m curious to see what kind of averages it settles down to once I stop paying attention to it. I know I usually waste quite a lot more time chatting with people on Trillian and browsing FFYa than it shows I did today. I’ll post some pictures when it’s collected a little more demographics.

    Oh yeah, the basic personal account is free and you have the option of linking it right into your Google sign-on (which I did).

    Enjoy obsessing over your own work habits!


    I personally don't use it anymore. I figured out that for me, I could only motivate so much productivity with this game of self improvement and statistics. Better long term solution was to find jobs that were more interesting than the latest trending topics on Skeptics Exchange.

    That being said, here I am, answering your question at work. :p

    0 讨论(0)
  • 2021-02-07 08:30

    There are many tools to do this like RescueTime etc... but you could use some .net code to knock up an approximation quite quickly.

    You would need to poll the list of processes at some given interval,

    psList = Process.GetProcesses() 
    

    You could use the starttime property and the main window title to get information about each process. I am not sure how to tell which one is active or not.

    0 讨论(0)
  • 2021-02-07 08:36

    This guy, Sateesh Arveti, coded what you are looking for: Active Application Watcher:

    Up to now, I have seen so many applications that will show system usage in terms of memory, processor...But, A user don't want this all details. He May expect to know how much time, he is spending on each application like browser, Winamp by the end of day...This application will help out a user to know how much time , he is spending on each application every day. This application assumes that the window, which is active as the application on which the user is working. So, it will log that application details like window title, process name and time spent on it in an xml file. It will continue like that until the application is closed. Once the application is closed, it will show entire active application's details in a browser with proper format.

    Here is my simple vb.net version (I added the sound alert event for FireFox).

    enter image description here

    Create a WinTracker class:

    Imports System
    Imports System.ComponentModel
    
    Public Class WinTracker
      Implements INotifyPropertyChanged
      Public Event PropertyChanged(ByVal sender As Object, ByVal e As PropertyChangedEventArgs) Implements INotifyPropertyChanged.PropertyChanged
      Public Event SoundAlert(ByVal sender As Object, ByVal e As EventArgs)
    
      Private _ID As Integer
      Private _Text As String
      Private _ElapsedTime As TimeSpan
      Private _LastStart As DateTime
      Private _RunningTime As TimeSpan
    
      Public Sub New(ByVal id As Integer, ByVal text As String)
        _ID = id
        _Text = text
        Call StartTracking()
      End Sub
    
      ReadOnly Property ID() As Integer
        Get
          Return _ID
        End Get
      End Property
    
      Property Text() As String
        Get
          Return _Text
        End Get
        Set(ByVal value As String)
          If value <> _Text Then
            _Text = value
            RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs("Text"))
          End If
        End Set
      End Property
    
      Public Sub StartTracking()
        _RunningTime = TimeSpan.Zero
        _LastStart = DateTime.Now
      End Sub
    
      Public Sub StopTracking()
        _ElapsedTime += _RunningTime
        _RunningTime = TimeSpan.Zero
        RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs("ToString"))
      End Sub
    
      Public Sub UpdateTime()
        _RunningTime = (DateTime.Now - _LastStart)
        RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs("ToString"))
    
        If _RunningTime.Seconds >= 60 Then
          RaiseEvent SoundAlert(Me, New EventArgs)
        End If
      End Sub
    
      Public Overrides Function ToString() As String
        Return "(" & FormatTimeSpan(_ElapsedTime + _RunningTime) & ")   " & _Text
      End Function
    
      Public Shared Operator =(ByVal thisItem As WinTracker, ByVal thatItem As WinTracker) As Boolean
        Return (thisItem.ID = thatItem.ID)
      End Operator
    
      Public Shared Operator <>(ByVal thisItem As WinTracker, ByVal thatItem As WinTracker) As Boolean
        Return Not (thisItem.ID = thatItem.ID)
      End Operator
    
      Private Function FormatTimeSpan(ByVal span As TimeSpan) As String
        Return span.Hours.ToString("00") & " hrs " & span.Minutes.ToString("00") & " min " & span.Seconds.ToString("00") & " sec"
      End Function
    
      Public Shared Sub SwitchWindows(ByVal FromWindow As WinTracker, ByVal ToWindow As WinTracker)
        FromWindow.StopTracking()
        ToWindow.StartTracking()
      End Sub
    
    End Class
    

    And then create a form with a timer and a listbox:

    Imports System
    Imports System.ComponentModel
    Imports System.Diagnostics
    Imports System.Runtime.InteropServices
    
    Public Class Form1
      Private Declare Auto Function GetForegroundWindow Lib "user32" () As IntPtr
      Private Declare Auto Function GetWindowThreadProcessId Lib "user32" (ByVal hWnd As Int32, ByRef lpdwProcessId As Int32) As UInt32
    
      Private _Windows As New BindingList(Of WinTracker)
      Private _ActiveWindow As WinTracker
    
      Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
        With ListBox1
          .ValueMember = "ID"
          .DisplayMember = "ToString"
          .DataSource = New BindingSource(_Windows, Nothing)
        End With
        Timer1.Enabled = True
      End Sub
    
      Private Sub Timer1_Tick(ByVal sender As Object, ByVal e As EventArgs) Handles Timer1.Tick
        Dim hWnd As Integer = GetForegroundWindow().ToInt32
    
        If hWnd > 0 Then
          Dim id As Integer = 1
          Call GetWindowThreadProcessId(hWnd, id)
          If id > 0 Then
            Dim text As String = Process.GetProcessById(id).ProcessName
    
            If text <> String.Empty Then
              Dim spent As WinTracker = _Windows.FirstOrDefault(Function(x As WinTracker) x.ID = id)
              If spent Is Nothing Then
                spent = New WinTracker(id, text)
                _Windows.Add(spent)
    
                If text.ToLower = "firefox" Then
                  AddHandler spent.SoundAlert, AddressOf WinTracker_SoundAlert
                End If
    
              Else
                spent.Text = text
              End If
    
              If _ActiveWindow Is Nothing Then
                _ActiveWindow = spent
              Else
                If _ActiveWindow <> spent Then
                  WinTracker.SwitchWindows(_ActiveWindow, spent)
                  _ActiveWindow = spent
                Else
                  _ActiveWindow.UpdateTime()
                End If
              End If
    
            End If
          End If
        End If
      End Sub
    
      Private Sub WinTracker_SoundAlert(ByVal sender As Object, ByVal e As EventArgs)
        My.Computer.Audio.PlaySystemSound(Media.SystemSounds.Beep)
      End Sub    
    
    End Class
    

    Refactor as needed.

    0 讨论(0)
  • 2021-02-07 08:37

    Probably you should try firefox add-on then,
    here is the link https://addons.mozilla.org/en-US/firefox/addon/timetracker/

    0 讨论(0)
  • 2021-02-07 08:44

    Here is almost the entire source for a WinForms app that does this. Note that it only adds time when Firefox has focus.

    using System;
    using System.Diagnostics;
    using System.Runtime.InteropServices;
    using System.Windows.Forms;
    
    namespace FireFoxWatch
    {
      public partial class Form1 : Form
      {
        [DllImport("user32.dll")]
        private static extern IntPtr GetForegroundWindow();
    
        [DllImport("user32.dll", SetLastError = true)]
        static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
    
        private TimeSpan fireFoxElapsedTime = new TimeSpan();
    
        public Form1()
        {
          InitializeComponent();
        }
    
        // this handler is called each time the Timer component's interval is reached.
        private void timer1_Tick(object sender, EventArgs e)
        {
          var wnd = GetForegroundWindow();
          uint procId;
          GetWindowThreadProcessId(wnd, out procId);
    
          var process = Process.GetProcessById((int)procId);
          if (process.ProcessName.Equals("firefox", StringComparison.CurrentCultureIgnoreCase))
            fireFoxElapsedTime += new TimeSpan(0, 0, 0, 0, timer1.Interval);
    
          //TODO: If fireFoxElapsedTime > Some predetermined TimeSpan, play a sound.
          // Right now it just updates a display label.
          label1.Text = fireFoxElapsedTime.ToString();
        }
    
        // start the timer when the form loads.
        private void Form1_Load(object sender, EventArgs e)
        {
          timer1.Start();
        }
      }
    }
    

    The only part not shown here, is that I made a default WinForms app, then added a "Timer" component from the toolbox, which is named "timer1" in the code, and was the default name.

    The above code just updates the total time on a winform label, but you could easily add code to play a sound.

    0 讨论(0)
  • 2021-02-07 08:50

    This is not a programming problem. This is a discipline problem. My advises:

    1. First of all, don't rely on application to tell you what to do.
    2. Secondly, the application can warn you but ultimately you can disable it, turn it off.
    3. Thirdly, my suggestion to your real problem i.e. no discipline and poor work ethic is to put up a small banner in front of your monitor with this text "Focus on your work" or "Code it now" or "SO is evil"
    0 讨论(0)
提交回复
热议问题