Using JXA to pause Time Machine for 30 mins

A Javascript for Automation (JXA) script (for an Execute Shell Script action), which either switches Time Machine OFF or ON, depending on the state of a TimeMachineON KM variable.

For use, for example, in a macro which suspends Time Machine for 30 mins, and later notifies that it has been restarted.

Sample KM macro in which the same JXA script is used twice – once for OFF and once for ON (text of script below):

osascript -l JavaScript << END_JXA_SCRIPT
function run() {
	'use strict';
	function switchTimeMachine(blnOn) {

		var strOnOff = (blnOn ? 'ON' : 'OFF'),
			appSE = new Application("System Events"),
			appPrefs = new Application("System Preferences"),
			btn;

		// Open Time Machine Prefs window,
		appPrefs.activate();
		appPrefs.panes.byId(
			"com.apple.prefs.backup"
		).anchors.byName(
			"main"
		).reveal();
		
		appSE.activate();

		// find the button we want
		btn = appSE.applicationProcesses.byName(
			"System Preferences"
		).windows.byName(
			"Time Machine"
		).buttons.byName(strOnOff);

		// click it
		appSE.click(btn);

		// and close the sys prefs window
		appPrefs.preferencesWindow.close();
		return strOnOff;
	}

	function findOrMakeKMVar(strName) {
		var appKM = new Application("Keyboard Maestro Engine"),
			oVars = appKM.variables;

		try {
			oVars[strName].name();
		} catch (e) {
			oVars.push(appKM.Variable({
				'name': strName
			}));
		}
		return oVars[strName];
	}

	function jsBool(strBool) {
		return strBool === "true";
	}

	/// MAIN: switch to the state indicated by a KeyBoard Maestro variable
	var strKMVarName = "TimeMachineON",
		oFlag = findOrMakeKMVar(strKMVarName),
		blnFlag = jsBool(oFlag.value()),
		varResult = switchTimeMachine(blnFlag);
	
	// err on the side of leaving the flag in the ON position
	oFlag.value = true;
		
	return varResult;
}
END_JXA_SCRIPT
1 Like