J Spen
J Spen

Reputation: 2674

Run cron job using emacsclient but if no server currently open run with emacs --batch mode

Due to emacs interlocking files I want to run org-mobile command via cron but using the emacsclient:

emacsclient -nw --eval "(org-mobile-pull)" --eval "(org-mobile-push)"

but if there is no emacs server running I want the command to run using emacs batch mode:

emacs --batch --eval "(org-mobile-pull)" --eval "(org-mobile-push)"

I'm not sure how to accomplish this so curious if anyone has any ideas.

Upvotes: 2

Views: 998

Answers (2)

event_jr
event_jr

Reputation: 17717

I'm curious what you're ultimately trying to accomplish? Why not just always start a new Emacs process? The additional overhead would be a small fraction of a second

On my 2 year old MBP:

% time emacs --batch --eval nil emacs --batch --eval nil 0.03s user 0.01s system 87% cpu 0.054 total

Going down your current path, you can check the exit code from emacsclient to decide if you should run in batch

if emacsclient --eval nil >/dev/null 2>&1; then echo "run client"; else echo "run emacs"; fi

EDIT: I see you want to script an answer to the lock stealing question. Check out my answer to this question for using ask-user-about-lock to solve this.

EDIT: So the idea is to redefine ask-user-about-lock to return t. See docs:

ask-user-about-lock is an autoloaded Lisp function in `userlock.el'.

(ask-user-about-lock FILE OPPONENT)

Ask user what to do when he wants to edit FILE but it is locked by OPPONENT. This function has a choice of three things to do: do (signal 'file-locked (list FILE OPPONENT)) to refrain from editing the file return t (grab the lock on the file) return nil (edit the file even though it is locked). You can redefine this function to choose among those three alternatives in any way you like.

[back]

script example (remember to chmod)

#!/usr/bin/env emacs --script

(defun ask-user-about-lock (file opponent)
  t)

(org-mobile-pull)
(org-mobile-push)

Upvotes: 6

Thomas
Thomas

Reputation: 17422

The emacsclient returns an error code if the server is not running. If you are certain that the code you want to eval will make emacsclient exit normally, then the following should work:

emacsclient -nw --eval "(org-mobile-pull)" --eval "(org-mobile-push)" 2>/dev/null || emacs --batch --eval "(org-mobile-pull)" --eval "(org-mobile-push)"

Note however that this simple approach discards potential error messages you might be interested in (but only in the case where emacsclient is run).

Upvotes: 1

Related Questions