Advertisement

Track Project Time With Alfred Timekeeper

by

This Cyber Monday Tuts+ courses will be reduced to just $3 (usually $15). Don't miss out.

Final product image
What You'll Be Creating

Alfred Time Keeper

Many people juggle multiple projects with different time schedules. From web apps to dedicated programs, there’s already a number of ways to keep track of time spent on a project. Most require net service and/or a program to stay running all the time. Often this isn’t practical.

Alfred Timekeeper works similar to a punch card time keeping system: you save a timestamp when you start and stop working. Since it just records timestamps, a program or web service isn’t always open.

In this tutorial, I'll assume that you’re already familiar with writing workflows in Alfred. If not, please check out these tutorials: Alfred for Beginners, Intermediates, Advanced users and Alfred Debugging.

Overall Design

Many people work with different computers in different locations. That makes keeping track of projects and time management that much harder. By using Dropbox, all of the project and time management information is synchronized automatically.

This approach necessitates the keeping of all information in files and not in computer memory. This restriction requires the use of two data storage arrangements: local directory of information used by that system’s program only, and a synchronized directory that’s shared with every computer connected to it.

The local storage contains the reference to the synchronized directory and the editor to edit timesheets. These files are in Alfred’s data directory location.

The synchronized directory keeps all the timesheets, lists of projects, last known state of recording information, and the timezone information. That will be in a Dropbox location. Any file system synchronization system can be used, I just happen to have Dropbox already.

Creating the Workflow

In Alfred, create a new workflow called Alfred Timekeeper.

Creating the Workflow
Creating the Workflow

In this new workflow, you need to create a File Filter that will only list directories.

Set Timesheet Directory Command
Set Timesheet Directory Command

You can set the File Types by dragging a directory from Finder to the File Types area. Set the Search Scope to the directory that contains your DropBox account.

Add a Run Script block after this block, unselecting all the escaping options. To that block, add this script:

#########################
# Contants.
#########################
VPREFS="${HOME}/Library/Caches/com.runningwithcrayons.Alfred-2/Workflow Data/"
NVPREFS="${HOME}/Library/Application Support/Alfred 2/Workflow Data/"

##############################################################################
# Read the bundleid from the workflow's info.plist
##############################################################################
getBundleId() {
  /usr/libexec/PlistBuddy  -c "Print :bundleid" "info.plist"
}

##############################################################################
# Get the workflow data dir
##############################################################################
getDataDir() {
  local BUNDLEID=$(getBundleId)
  echo "${NVPREFS}${BUNDLEID}"
}

if [ ! -d "$(getDataDir)" ]; then
   mkdir -p "$(getDataDir)";
   touch "$(getDataDir)/dir.txt";
   touch "$(getDataDir)/editor.txt";
fi

# Store the directory information.
echo "{query}" > "$(getDataDir)/dir.txt";

# Tell the user.
echo "Set directory to '{query}'.";

This script checks for the data directory to be there. If not there, it creates the directory and the files used for the workflow. It takes the input in the {query} macro and places it in the dir.txt file in the data directory. It then notifies the user of the action.

Connect the Run Script block to a notification block. All Run Script blocks from here on should connect to this notification block. Set its output to be the {query} macro and set the Only show if passed in argument has content.

Once saved, set the timesheet directory. Inside the Dropbox directory, create a directory for timesheets and use the atk:setdir command to set that directory. You’re now running a multiple system timekeeping program!

That's the basic setup routine for the workflow. Before tackling the main program, you need to setup the working environment.

Setting Up the Go Environment

The easiest way to install the go programming language is by Homebrew. If you haven’t installed Homebrew yet, the tutorial Homebrew Demystified: OS X’s Ultimate Package Manager will show you how.

In a terminal, type:

brew install go

In the home directory, create the directory go. The go language will store all downloaded libraries there. Add to the .bashrc file and/or .zshrc file this line:

export GOPATH="/Users/<your user name>/go"

If you’re using fish, add this to the config.fish file:

set -xg GOPATH "/Users/<your user name>/go"

After reloading shell, you can install the goAlfred library by typing:

go get github.com/raguay/goAlfred

This library makes using the go language with Alfred much easier. It will create the directories to the data storage area for Alfred workflows and make the XML listing needed in Script Filters.

Timekeeper.go

To create the main program file, you have to go to the directory for the workflow. Open the Run Script block.

Opening the Workflow Directory
Opening the Workflow Directory

Click the Open workflow folder button at the bottom of the Script: area. This opens the workflow directory in Finder (or Pathfinder if you have it). To open the directory in a terminal shell, you can use the Alfred Workflow TerminalFinder to open a Finder or Path Finder directory in a terminal session (or iTerm).

Creating the Program File in Terminal
Creating the Program File in Terminal

Once in the terminal program, type:

touch Timekeeper.go

Open that file in the editor of choice. Once open, put this code in:

package main

//
// Program:              TimeKeeper.go
//
// Description:         This program runs the feedback logic for selecting  the on/off state for
//                              the currently timed project.
//

//
// Import the libraries we use for this program.
//
import (
    "fmt"
    "github.com/raguay/goAlfred"
    "io"
    "io/ioutil"
    "os"
    "regexp"
    "strconv"
    "strings"
    "time"
)

//
// Setup and constants that are used.
//
// MAXPROJECTS            This is the maximum number of projects allowed.
// TSDir                         This keeps the directory name for the time sheets. It is a complete path.
//
const (
    MAXPROJECTS int = 20
)

var TSDir = ""

//
// Function:           main
//
// Description:       This is the main function for the TimeKeeper program. It takes the command line
//                          and parses it for the proper functionality.
//
func main() {
    if len(os.Args) > 1 {
        switch os.Args[1][0] {
        case 'm':
            //
            // atk:month
            //
            SystemViewMonth()
        case 'w':
            //
            // atk:week
            //
            SystemViewWeek()
        case 't':
            //
            // atk:current
            //
            SystemViewDate()
        case 'r':
            //
            // atk:remove
            //
            RemoveProject()
        case 'c':
            //
            // atk:project
            //
            ChangeProject()
        case 'b':
            //
            // atk:current
            //
            SystemViewDay()
        case 'a':
            //
            // atk:addproject
            //
            AddProject()
        case 'o':
            //
            // atk:state
            //
            StopStart()
        case 'p':
            //
            // Used for atk:project script fileter
            //
            project()
        case 'T':
            //
            // atk:time
            //
            SystemAllProjects()
        case 's':
            fallthrough
        default:
            //
            // Used for the script filter on atk:state
            //
            state()
        }
    }
}

//
// Function:        getTimeSheetDir
//
// Description:     This function is used to cache a copy of the time
//                  sheet directory and give it in the return.
//
func getTimeSheetDir() string {
    if strings.Contains("", TSDir) {
        Filename := goAlfred.Data() + "/dir.txt"
        buf, err := ioutil.ReadFile(Filename)
        if err == nil {
            //
            // Convert the directory path to a string and trim it.
            //
            TSDir = strings.TrimSpace(string(buf))
        }
    }

    //
    // Return the directory to the time sheets.
    //
    return (TSDir)
}

//
// Function:              SystemAllProjects
//
// Description:          This function will display to the terminal the time for all projects on
//                             the day given on the command line next.
//
func SystemAllProjects() {
    //
    // Get the current date in case there isn't one on the command line.
    //
    tm := time.Now()
    if len(os.Args) > 2 {
        if strings.Contains("today", os.Args[2]) {
            //
            // Today's date.
            //
            tm = time.Now()
        } else if strings.Contains("yesterday", os.Args[2]) {
            //
            // Yesterday is today minus one day.
            //
            tm = time.Now()
            tm = tm.AddDate(0, 0, -1)
        } else {
            //
            // Parse the date string given.
            //
            tm, _ = time.Parse("2006-Jan-02", os.Args[2])
        }
    }

    //
    // Get the list of project names.
    //
    proj := GetListOfProjects()

    //
    // For each project, get the time spent on it for the given day.
    //
    numproj := len(proj) - 1
    for i := 0; i < numproj; i++ {
        fmt.Printf("%s: %s\n", proj[i], formatTimeString(GetTimeAtDate(proj[i], tm)))
    }
}

//
// Function:           SystemViewMonth
//
// Description:       This function will calculate the time the current month for all the projects.
//
func SystemViewMonth() {
    //
    // Get the current project.
    //
    currentProject := GetCurrentProject()

    //
    // Get the time on that project for this month. The current time gives the current month.
    //
    tm := GetTimeAtMonth(currentProject, time.Now())

    //
    // format the time string and print it out.
    //
    fmt.Print(formatTimeString(tm))
}

//
// Function:           GetTimeAtDate
//
// Description:       This function will take a project and calculate the time spent
//                          on that project for a particular date.
//
func GetTimeAtMonth(project string, date time.Time) int64 {
    tm := int64(0)
    dateStart := time.Date(date.Year(), date.Month(), 1, 0, 0, 0, 0, time.UTC)

    //
    // Get the time added up for the whole week.
    //
    for i := 0; i <= date.Day(); i++ {
        tm += GetTimeAtDate(project, dateStart.AddDate(0, 0, i))
    }

    //
    // Return the amount of time calculated.
    //
    return (tm)
}

//
// Function:           SystemViewWeek
//
// Description:       This function will calculate the time the current week for all the projects.
//
// Inputs:
//      variable    description
//
func SystemViewWeek() {
    currentProject := GetCurrentProject()
    tm := GetTimeAtWeek(currentProject, time.Now())
    fmt.Print(formatTimeString(tm))
}

//
// Function:           GetTimeAtDate
//
// Description:       This function will take a project and calculate the time spent
//                          on that project for a particular date.
//
func GetTimeAtWeek(project string, date time.Time) int64 {
    tm := int64(0)
    dateStart := date
    dateEnd := date
    switch date.Weekday() {
    case 0:
        {
            dateEnd = dateEnd.AddDate(0, 0, 6)
        }
    case 1:
        {
            dateStart = dateStart.AddDate(0, 0, -1)
            dateEnd = dateEnd.AddDate(0, 0, 5)
        }
    case 2:
        {
            dateStart = dateStart.AddDate(0, 0, -2)
            dateEnd = dateEnd.AddDate(0, 0, 4)
        }
    case 3:
        {
            dateStart = dateStart.AddDate(0, 0, -3)
            dateEnd = dateEnd.AddDate(0, 0, 3)
        }
    case 4:
        {
            dateStart = dateStart.AddDate(0, 0, -4)
            dateEnd = dateEnd.AddDate(0, 0, 2)
        }
    case 5:
        {
            dateStart = dateStart.AddDate(0, 0, -5)
            dateEnd = dateEnd.AddDate(0, 0, 1)
        }
    case 6:
        {
            dateStart = dateStart.AddDate(0, 0, -6)
        }
    }
    //
    // Get the time added up for th whole week.
    //
    for i := 0; i < 7; i++ {
        tm += GetTimeAtDate(project, dateStart.AddDate(0, 0, i))
    }
    return (tm)
}

//
// Function:           SystemViewDate
//
// Description:       This function will calculate the time for projects at a certain date.
//
func SystemViewDate() {
    currentProject := GetCurrentProject()
    tm := GetTimeAtDate(currentProject, time.Now())
    fmt.Print(formatTimeString(tm))
}

//
// function:            SystemViewDay
//
// Description:        This function is for displaying a nice time for the current project.
//
func SystemViewDay() {
    currentProject := GetCurrentProject()
    tm := GetTimeAtDate(currentProject, time.Now())
    ctime := formatTimeString(tm)
    state := GetCurrentState()
    fmt.Printf("The current time on %s is %s. Current state is %s.", currentProject, ctime, state)
}

//
// Function:           GetTimeAtDate
//
// Description:       This function will take a project and calculate the time spent
//                          on that project for a particular date.
//
func GetTimeAtDate(project string, date time.Time) int64 {
    //
    // Get the current project.
    //
    filename := generateTimeLogFileName(project, date)
    tm := readDayTime(filename)
    return tm
}

//
// Function:             formatTimeString
//
// Description:         This function takes the number of seconds and returns a string
//                            in hour:minute:seconds format with zero padding.
//
// Input:
//                            tm          time in seconds (an int64)
//
func formatTimeString(tm int64) string {
    min := int(tm / 60)
    sec := tm - int64(min*60)
    hr := min / 60
    min = min - (hr * 60)
    return fmt.Sprintf("%02d:%02d:%02d", hr, min, sec)
}

//
// Function:             readDayTime
//
// Description:         This function reads a time sheet file and calculates the time
//                            represented in that file.

func readDayTime(filename string) int64 {
    buf, _ := ioutil.ReadFile(filename)
    times := regexp.MustCompile("\n|\r").Split(string(buf), -1)

    //
    // Loop through all the time lines.
    //
    tmwork := int64(0)
    firsttime := int64(0)
    first := false
    for i := 0; i < len(times); i++ {
        if !strings.Contains("", times[i]) {
            //
            // Split by colon to time and action.
            //
            parts := strings.Split(times[i], ":")
            if strings.Contains("start", parts[1]) {
                firsttime, _ = strconv.ParseInt(parts[0], 10, 64)
                first = true
            } else {
                tm, _ := strconv.ParseInt(parts[0], 10, 64)
                tmwork += tm - firsttime
                first = false
            }
        }
    }

    //
    // If a start was the last thing processed, that means it is still being timed. Get the
    // current time to see the overall time. firsttime is the time stamp when the start
    // was given.
    //
    if first {
        currentTime := time.Now()
        ctime := currentTime.Unix()
        tmwork += ctime - firsttime
    }
    //
    // Return the final Time.
    //
    return tmwork
}

//
// Function:           RemoveProject
//
// Description:       This function will remove a project from the list a valid projects.
//
func RemoveProject() {
    //
    // Get the project name from the command line.
    //
    proj := GetCommandLineString()

    //
    // Get the list of project names.
    //
    projects := GetListOfProjects()

    //
    // Open the projects file in truncation mode to remove all the old stuff.
    //
    Filename := getTimeSheetDir() + "/projects.txt"
    Fh, err := os.OpenFile(Filename, os.O_TRUNC|os.O_WRONLY|os.O_CREATE, 0666)
    if err != nil {
        //
        // The file would not open. Error out.
        //
        fmt.Print("Could not open the  projects file: ", Filename, "\n")
        os.Exit(1)
    }

    //
    // Loop through all the projects.
    //
    for i := 0; i < len(projects); i++ {
        if !strings.Contains(proj, projects[i]) {
            //
            // It is not the project to be removed. Put it into the file.
            //
            Fh.WriteString(projects[i] + "\n")
        }
    }

    //
    // Close the file.
    //
    Fh.Close()

    //
    // Tell the user that the project has been removed.
    //
    fmt.Print(proj + " has been removed!")
}

//
// Function:           ChangeProject
//
// Description:       This function will change the currently active project. If the old
//                            project was started, it will stop it first, then set the new project
//                            and start it.
//
func ChangeProject() {
    //
    // Get the project name from the command line.
    //
    proj := GetCommandLineString()

    //
    // Get the current project.
    //
    currentProject := GetCurrentProject()

    //
    // Stop the current project.
    //
    StopStartProject(currentProject, "stop")

    //
    // Save the new project to the data file.
    //
    SaveProject(proj)

    //
    // Start the new project.
    //
    StopStartProject(proj, "start")

    //
    // Tell the user it is started.
    //
    fmt.Print("The current project is now " + proj + " and is  started.")
}

//
// Function:           GetCommandLineString
//
// Description:       This function is used to get the after the function if there is one.
//                             If not, then just return nothing.
//
func GetCommandLineString() string {
    //
    // See if we have any input other then the command.
    //
    clstring := ""
    if len(os.Args) > 2 {
        clstring = strings.TrimSpace(os.Args[2])
    }

    //
    // Return the the string.
    //
    return (clstring)
}

//
// Function:           AddProject
//
// Description:       This function will add a new project to the list of current projects.
//
func AddProject() {
    //
    // Get the project name from the command line.
    //
    proj := GetCommandLineString()

    //
    // Create the file name that contains all the projects.
    //
    projectFile := getTimeSheetDir() + "/projects.txt"
    Fh, err := os.OpenFile(projectFile, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0666)
    if err != nil {
        Fh, err = os.Create(projectFile)
        if err != nil {
            //
            // The file would not open. Error out.
            //
            fmt.Print("Could not open the projects file: ", projectFile, "\n")
            os.Exit(1)
        }
    }

    //
    // Write the new command with the time stamp to the buffer.
    //
    _, err = io.WriteString(Fh, proj+"\n")

    //
    // Lose the file.
    //
    Fh.Close()

    //
    // Tell the user that the project is added.
    //
    fmt.Print("Added project " + proj + " to the list.")
}

//
// Function:           state
//
// Description:       This function gives the proper output for changing the state. The state
//                            first is the one opposite from the current state.
//
func state() {
    //
    // Get the last state of the current project.
    //
    stateFile := getTimeSheetDir() + "/laststate.txt"
    buf, _ := ioutil.ReadFile(stateFile)
    curState := string(buf)

    //
    // Set the first command to the opposite of the current state. That way
    // the user simply pushes return to toggle states.
    //
    if strings.Contains(curState, "start") {
        goAlfred.AddResult("stop", "stop", "stop", "", "icon.png", "yes", "", "")
        goAlfred.AddResult("start", "start", "start", "", "icon.png", "yes", "", "")
    } else {
        goAlfred.AddResult("start", "start", "start", "", "icon.png", "yes", "", "")
        goAlfred.AddResult("stop", "stop", "stop", "", "icon.png", "yes", "", "")
    }

    //
    // Print out the xml string.
    //
    fmt.Print(goAlfred.ToXML())
}

//
// Function:           project
//
// Description:       This function creates a list of the projects and displays the ones
//                            similar to the input.
//
func project() {
    //
    // Get the project name from the command line.
    //
    proj := GetCommandLineString()

    //
    // Set our default string.
    //
    goAlfred.SetDefaultString("Alfred Time Keeper:  Sorry, no match...")

    //
    // Get the latest project.
    //
    latestproject := GetCurrentProject()

    //
    // Get the list of projects.
    //
    projects := make([]string, MAXPROJECTS)
    projects = GetListOfProjects()

    //
    // The regexp split statement gives one string more than was split out. The last
    // string is a catchall. It does not need to be included.
    //
    numproj := len(projects) - 1

    //
    // For each project, create a result line. Show all put the current project.
    //
    for i := 0; i < numproj; i++ {
        if !strings.Contains(projects[i], latestproject) {
            goAlfred.AddResultsSimilar(proj, projects[i], projects[i], projects[i], "", "icon.png", "yes", "", "")
        }
    }

    //
    // Print out the xml string.
    //
    fmt.Print(goAlfred.ToXML())
}

//
// Function:           GetListOfProjects
//
// Description:       This function will return an array of string with the names of the project.
//
func GetListOfProjects() []string {
    //
    // Create the projects array and populate it.
    //
    projectFile := getTimeSheetDir() + "/projects.txt"
    buf, _ := ioutil.ReadFile(projectFile)

    //
    // Split out the different project names into separate strings.
    //
    return (regexp.MustCompile("\n|\r").Split(string(buf), -1))
}

//
// Function:           StopStart
//
// Description:       This will place a start or stop time stamp for the current project and
//                            current date.
//
func StopStart() {
    //
    // See if we have any input other then the command.  If not, assume a stop command.
    //
    cmd := "stop"
    if len(os.Args) > 2 {
        cmd = strings.ToLower(os.Args[2])
    }

    //
    // Get the current project.
    //
    currentProject := GetCurrentProject()

    //
    // Run the appropriate function and print the results.
    //
    fmt.Print(StopStartProject(currentProject, cmd))
}

//
// Function:           GetCurrentProject
//
// Description:       This function will retrieve the current project from the
//                            state file.
//
func GetCurrentProject() string {
    //
    // Get the current project.
    //
    Filename := getTimeSheetDir() + "/project.txt"
    buf, _ := ioutil.ReadFile(Filename)

    //
    // Convert the current project to a string, trim it, and return it.
    //
    return (strings.TrimSpace(string(buf)))
}

//
// Function:           SaveProject
//
// Description:       This function will save the given project name to the
//                            current project file.
//
// Inputs:
//      proj         Name of the new project
//
func SaveProject(proj string) {
    //
    // Write the new project.
    //
    Filename := getTimeSheetDir() + "/project.txt"
    err := ioutil.WriteFile(Filename, []byte(proj), 0666)
    if err != nil {
        fmt.Print("Can not write the project file: " + Filename)
        os.Exit(1)
    }
}

//
// Function:           StopStartProject
//
// Description:       This function is used to set the state for the given project.
//
// Inputs:
//      currentProject  The project to effect the state of.
//               cmd                    The start or stop command.
//
func StopStartProject(currentProject string, cmd string) string {
    //
    // Setup the result string.
    //
    resultStr := ""

    currentState := GetCurrentState()

    //
    // Is the current state the same as the new state?
    //
    if strings.Contains(cmd, currentState) {
        //
        // It is already in that state. Do nothing, but give a message.
        //
        resultStr = "Already " + cmd + "\n"
    } else {
        //
        // Okay, we can proceed with writing the new state into the
        // dated project file. Open the file for writing.
        //
        currentTime := time.Now()
        Filename := generateTimeLogFileName(currentProject, currentTime)
        Fh, err := os.OpenFile(Filename, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0666)
        if err != nil {
            //
            // The file would not open. Error out.
            //
            fmt.Print("Could not open the dated project file: ", Filename, "\n")
            os.Exit(1)
        }

        //
        // Write the new command with the time stamp to the buffer.
        //
        str := fmt.Sprintf("%d:%s\n", currentTime.Unix(), cmd)
        _, err = io.WriteString(Fh, str)

        //
        // Lose the file.
        //
        Fh.Close()

        //
        // Write the laststate file with the new state.
        //
        ioutil.WriteFile(getTimeSheetDir()+"/laststate.txt", []byte(cmd), 0666)

        //
        // Tell the user it is set.
        //
        resultStr = currentProject + " is now " + cmd
    }

    //
    // Return the resulting string.
    //
    return (resultStr)
}

//
// function:                GetCurrentState
//
// Description:           This function gets the current state of the project.
//
func GetCurrentState() string {
    //
    // Get the current state.
    //
    Filename := getTimeSheetDir() + "/laststate.txt"
    buf, err := ioutil.ReadFile(Filename)
    currentState := "stop"
    if err == nil {
        //
        // Convert the current project to a string and trim it.
        //
        currentState = strings.TrimSpace(string(buf))
    }
    return currentState
}

//
// Function:           generateTimeLogFileName
//
// Description:       This functions creates the time log file based on the project name and
//                            date.
//
// Inputs:
//      proj         Name of the project
//               dt           Date in question
//
func generateTimeLogFileName(proj string, dt time.Time) string {
    //
    // Generate the proper file name based on the project name and date.
    //
    filename := getTimeSheetDir() + "/" + proj + "_" + dt.Format("2006-01-02") + ".txt"
    return (filename)
}

That code defines all the functionality of the Alfred Timekeeper. The design of the program is to do different functions based on a command letter and options parameters after it. It will get the timesheet directory from Alfred and create the project files and timesheets as needed.

Compiling

You have to compile the program before you can use it. The go language isn’t an interpreted language, but a compiled language. This allows the program to run much faster.

In the terminal program, type:

go build Timekeeper.go
Compiling Timekeepergo
Compiling Timekeeper.go

If everything is in place properly, you should now have the Timekeeper program in that directory. It is in red above. If something did not get copied right and the compile fails, lookup the line number given and compare it to the above. Or, get a fresh copy from the download given with this tutorial.

Adding Alfred Functions

With the program finished, you need to call it from Alfred. Create a Keyword block with the keyword set to atk:addproject. Connect it to a Run Script block and put this line of code:

./TimeKeeper a "{query}"

All Run Scripts blocks here on out should be set to run bash scripts and none of the escaping options set. The above script allows for creating new projects. Use this to create your different projects. I have the projects: Envato, CustomCT, and Missions created for the work I do.

Now that you have projects, you now need to set one as the current project. Create a Script Filter as below:

Script Filter for Selecting a Project
Script Filter for Selecting a Project

Add a Run Script block after it with the following script:

./Timekeeper c "{query}"
Setting the Project
Setting the Project

Now, you can set the project you want to work on. In the Alfred Prompt, type atk:project and a list of the created projects should appear. Select the project you want and it will automatically start timing for you.

Therefore, if you selected the Tutorials project, there is a file named Tutorials_2014–05–05.txt (that is, as long as you created it on May 5, 2014). Inside that file is a time stamp, a colon, and a start statement. You will also have the project.txt file with the currently selected project, laststate.txt file with the last state (ie: start or stop), and the projects.txt file with a list of created projects.

The timing has started, but now you need to stop it. Create a new Script Filter block with the keyword set to atk:state and the script set to:

./TimeKeeper s "{query}"

That should connect to a Run Script block with the script set to:

./TimeKeeper o "{query}"

The s command tells Timekeeper program to generate an XML output for the next state. It will automatically have the first option in the XML to be the opposite of the current state.

Changing Timing States
Changing Timing States

You can now toggle the state of timing a project with atk:state. You can also create hotkeys to start and stop the timing. Try to do that one on your own. You never learn until you try!

Adding an External Trigger
Adding an External Trigger

You might want an external program to set the state of time recording. Therefore, create a External Trigger block as shown. Connect this block to the previous Run Script block.

Adding an External Trigger - Configuration
Adding an External Trigger - Configuration

The Sample Code at the bottom can be ran by any AppleScript aware program to trigger start/stop actions on the current project. If you replace the text test with stop, it will stop timing. If you replace the text test with start, it will start timing. Used with ControlPlane, you can create a rule to turn off timing when the computer sleeps and resume timing when the computer wakes.

Now that you’re starting and stopping the time, you need to view the time spent. Create a Keyword block with atk:current. Connect it to a Run Script block with this script:

echo `./Timekeeper b`;

Connect it to the Notification block.

Current Time Command
Current Time Command

When you run atk:current in Alfred prompt, you will get the current time spent on the project and the current state.

Second Computer

If you have another computer, setup Alfred to share over Dropbox. Once set up, all of your workflows will automatically update from one computer to the other.

Setting Up Alfred Syncing
Setting Up Alfred Syncing

Select the Set sync folder to set up syncing via Dropbox and follow the directions. On the second computer, use the command atk:setdir to set the timesheet directory you created in Dropbox. The two systems can now start and stop project timings. Make sure Dropbox is fully synced in between state changes.

Conclusion

That’s the basics of the Alfred Timekeeper. The workflow packaged with the download is the full version with other features. You now understand how to create your own time management system that’s scalable to use on multiple computers using Dropbox and does not take up computer resources. 

Since I use this everyday, I will be adding more features such as a web interface to see the timesheets graphically. If you can come up with other features, try to add them yourself! That’s the fun of working with Alfred workflows.

Advertisement