<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Как сделать рабочие часы для скрипта]]></title><description><![CDATA[<p dir="auto">И так пока я обиваю пороги что бы меня взяли на работу, поделюсь своим решение как создать рабочие часы для любого скрипта в js.</p>
<p dir="auto">У нас имеется скрипт который выполняет какие-то действия скажем постоянно 24/7 и нам необходимо сделать так что бы он к примеру работал с 8 утра до 17 вечера.</p>
<p dir="auto">Вот наша часть которая запускает нашу функцию чего-либо:</p>
<pre><code class="language-js">setInterval(() =&gt; {
    periodicTask(arr).catch((err) =&gt; {
      console.error(`Ошибка блин...`, err);
    });
  }, intervalMs);
</code></pre>
<p dir="auto">Надеюсь всем понятно что <code>intervalMs</code> - это интервал с какой периодичностью необходимо выполнять действия.</p>
<p dir="auto">А теперь переходим к самому интересному, вот у нас есть функция <code>periodicTask</code> и нам нужно как-то откладывать задачи которые <code>setInterval()</code> на поставляет.</p>
<p dir="auto">Самый важный момент это то что сам <code>setInterval()</code> продолжает работать и не уходит в какую либо спячку дожидаться своего времени.</p>
<p dir="auto">Да можно было бы нагромоздить логики по типу “значит когда задача будет выполняться в интервале часов 16-17 мы меняет интервал на несколько часов” и т.п.</p>
<p dir="auto">Лишне все это лишнее! Заболталась что-то, продолжаем. Для дальнейшего нам потребуется сделать функцию нашего рабочего времени:</p>
<pre><code class="language-js">function workingHours(data = new Date()) {
    const hour = data.getHours();
    return hour &gt;= 8 &amp;&amp; hour &lt; 17;
}
</code></pre>
<p dir="auto">Понятно? Если нет то - мы в функции берем объект <code>Date</code> забираем от туда текущий час и возвращает наше будущее условие.</p>
<p dir="auto">Теперь возвращаемся к нашей функции <code>periodicTask</code>:</p>
<pre><code class="language-js">function periodicTask(arr) {

    if (!workingHours()) {
        console.log("Рабочий день уже закончился, не буду ничего делать!");
        return;
    }

    // Ну а дальше логика нашей задачи

}
</code></pre>
<p dir="auto">Понятно!!!??? Мы в самом начале функции <code>periodicTask</code> ставим условие для проверки времени рабочих часов, и если сейчас не рабочее время то <code>workingHours()</code> вернет нам <code>false</code>, в следствии чего вернет <code>return</code> и ничего не произойдет.</p>
<p dir="auto">Еще раз для закрепления - <code>return</code> не останавливает интервал, он всего лишь завершает текущий вызов <code>periodicTask</code>!!!<br />
Сам интервал живет отдельно, как и выше писала можно заморочиться нагромоздить всякой ерунды, но это более чем рабочий вариант.</p>
<blockquote>
<p dir="auto">p.s. С Ханной все сложное - легко, и да возьмите уже на работу <img src="https://forum.exlends.ru/assets/plugins/nodebb-plugin-emoji/emoji/android/1f625.png?v=a1e94250dac" class="not-responsive emoji emoji-android emoji--disappointed_relieved" style="height:23px;width:auto;vertical-align:middle" title=":disappointed_relieved:" alt="😥" /></p>
</blockquote>
]]></description><link>https://forum.exlends.ru/topic/351/kak-sdelat-rabochie-chasy-dlya-skripta</link><generator>RSS for Node</generator><lastBuildDate>Sat, 17 Oct 2026 03:12:35 GMT</lastBuildDate><atom:link href="https://forum.exlends.ru/topic/351.rss" rel="self" type="application/rss+xml"/><pubDate>Sun, 14 Dec 2025 13:54:01 GMT</pubDate><ttl>60</ttl><item><title><![CDATA[Reply to Как сделать рабочие часы для скрипта on Fri, 19 Dec 2025 13:58:27 GMT]]></title><description><![CDATA[<p dir="auto"><a class="plugin-mentions-user plugin-mentions-a" href="/user/dinozaur" aria-label="Profile: Dinozaur">@<bdi>Dinozaur</bdi></a><br />
<video id="/assets/uploads/files/ff/25/2b/1766152697034-photo_2021-01-07_01-25-51" src="/assets/uploads/files/ff/25/2b/1766152697034-photo_2021-01-07_01-25-51.mp4" controls style="max-width:100%;max-height:62dvh"></video></p>
]]></description><link>https://forum.exlends.ru/post/1207</link><guid isPermaLink="true">https://forum.exlends.ru/post/1207</guid><dc:creator><![CDATA[hannadev]]></dc:creator><pubDate>Fri, 19 Dec 2025 13:58:27 GMT</pubDate></item><item><title><![CDATA[Reply to Как сделать рабочие часы для скрипта on Wed, 17 Dec 2025 14:40:48 GMT]]></title><description><![CDATA[<p dir="auto">Очередной вкатун)))</p>
]]></description><link>https://forum.exlends.ru/post/1188</link><guid isPermaLink="true">https://forum.exlends.ru/post/1188</guid><dc:creator><![CDATA[Dinozaur]]></dc:creator><pubDate>Wed, 17 Dec 2025 14:40:48 GMT</pubDate></item><item><title><![CDATA[Reply to Как сделать рабочие часы для скрипта on Wed, 17 Dec 2025 13:31:14 GMT]]></title><description><![CDATA[<p dir="auto"><a class="plugin-mentions-user plugin-mentions-a" href="/user/mugiwara" aria-label="Profile: Mugiwara">@<bdi>Mugiwara</bdi></a> А вот как раз напрашивается вопрос производительности и оптимизации что лучшее поебывать <code>setInterval()</code> или <code>pm2</code><br />
Как говориться есть 2 стула))</p>
]]></description><link>https://forum.exlends.ru/post/1184</link><guid isPermaLink="true">https://forum.exlends.ru/post/1184</guid><dc:creator><![CDATA[kirilljsx]]></dc:creator><pubDate>Wed, 17 Dec 2025 13:31:14 GMT</pubDate></item><item><title><![CDATA[Reply to Как сделать рабочие часы для скрипта on Wed, 17 Dec 2025 13:20:38 GMT]]></title><description><![CDATA[<p dir="auto"><a class="plugin-mentions-user plugin-mentions-a" href="/user/kirilljsx" aria-label="Profile: kirilljsx">@<bdi>kirilljsx</bdi></a> Сначала надо понять какая цель у интервала, можно и без него  перезапускать скрипт после завершения через pm2, я же привел пример, когда надо задать именно интервал?   а так каждый газует как хочет,    вон, предложили  кронтаб использовать, самый простой и  производительный вариант.</p>
<p dir="auto">Но если ты скрипт будет  все равно на pm2 вешать, что скорее всего так и произойдет, то удобнее его интегрировать сразу. А если без  pm2,  то тебе еще ошибки ловить, как-то перезапускать если что-то не так</p>
]]></description><link>https://forum.exlends.ru/post/1183</link><guid isPermaLink="true">https://forum.exlends.ru/post/1183</guid><dc:creator><![CDATA[Mugiwara]]></dc:creator><pubDate>Wed, 17 Dec 2025 13:20:38 GMT</pubDate></item><item><title><![CDATA[Reply to Как сделать рабочие часы для скрипта on Wed, 17 Dec 2025 13:08:14 GMT]]></title><description><![CDATA[<p dir="auto"><a class="plugin-mentions-user plugin-mentions-a" href="/user/mugiwara" aria-label="Profile: Mugiwara">@<bdi>Mugiwara</bdi></a> То есть хочешь сказать отпадает смысл вообще в <code>setInterval()</code> ?</p>
]]></description><link>https://forum.exlends.ru/post/1182</link><guid isPermaLink="true">https://forum.exlends.ru/post/1182</guid><dc:creator><![CDATA[kirilljsx]]></dc:creator><pubDate>Wed, 17 Dec 2025 13:08:14 GMT</pubDate></item><item><title><![CDATA[Reply to Как сделать рабочие часы для скрипта on Wed, 17 Dec 2025 13:08:11 GMT]]></title><description><![CDATA[<p dir="auto"><a class="plugin-mentions-user plugin-mentions-a" href="/user/hannadev" aria-label="Profile: hannadev">@<bdi>hannadev</bdi></a><br />
пример скрипта который выполняет что-то</p>
<pre><code class="language-js">// script.js
async function main() {
    console.log(`[${new Date().toISOString()}] Запуск скрипта через PM2`);
    
    // Эмуляция работы
    await new Promise(r =&gt; setTimeout(r, 2000)); 
    console.log('Работа выполнена.');

    // ОБЯЗАТЕЛЬНО: завершаем процесс, чтобы PM2 не перезапускал его мгновенно,
    // а ждал следующего тика Cron.
    process.exit(0);
}

main();
</code></pre>
<p dir="auto">вот команда pm2 где <code>30</code> - количество минут  которое он ждет до следующего рестарта, нужно указать не меньше минут чем  время выполнения скрипта( его бы надо примерно знгать)</p>
<pre><code class="language-sh">pm2 start script.js --cron "*/30 8-17 * * *" --no-autorestart
</code></pre>
<p dir="auto">еще момент: pm2  работает так, что если выйдет ошибка - то скрипт сразу перезапускается</p>
]]></description><link>https://forum.exlends.ru/post/1181</link><guid isPermaLink="true">https://forum.exlends.ru/post/1181</guid><dc:creator><![CDATA[Mugiwara]]></dc:creator><pubDate>Wed, 17 Dec 2025 13:08:11 GMT</pubDate></item><item><title><![CDATA[Reply to Как сделать рабочие часы для скрипта on Wed, 17 Dec 2025 12:50:17 GMT]]></title><description><![CDATA[<p dir="auto"><a class="plugin-mentions-user plugin-mentions-a" href="/user/mugiwara" aria-label="Profile: Mugiwara">@<bdi>Mugiwara</bdi></a> Вот эта нормальная тема, а как в pm2 настроить такое то?</p>
]]></description><link>https://forum.exlends.ru/post/1179</link><guid isPermaLink="true">https://forum.exlends.ru/post/1179</guid><dc:creator><![CDATA[hannadev]]></dc:creator><pubDate>Wed, 17 Dec 2025 12:50:17 GMT</pubDate></item><item><title><![CDATA[Reply to Как сделать рабочие часы для скрипта on Wed, 17 Dec 2025 12:49:37 GMT]]></title><description><![CDATA[<p dir="auto"><a class="plugin-mentions-user plugin-mentions-a" href="/user/linus" aria-label="Profile: Linus">@<bdi>Linus</bdi></a> Вы чего напали то людоеды блин… <img src="https://forum.exlends.ru/assets/plugins/nodebb-plugin-emoji/emoji/android/1f627.png?v=a1e94250dac" class="not-responsive emoji emoji-android emoji--anguished" style="height:23px;width:auto;vertical-align:middle" title=":anguished:" alt="😧" /></p>
]]></description><link>https://forum.exlends.ru/post/1178</link><guid isPermaLink="true">https://forum.exlends.ru/post/1178</guid><dc:creator><![CDATA[hannadev]]></dc:creator><pubDate>Wed, 17 Dec 2025 12:49:37 GMT</pubDate></item><item><title><![CDATA[Reply to Как сделать рабочие часы для скрипта on Wed, 17 Dec 2025 12:49:20 GMT]]></title><description><![CDATA[<p dir="auto"><a class="plugin-mentions-user plugin-mentions-a" href="/user/mugiwara" aria-label="Profile: Mugiwara">@<bdi>Mugiwara</bdi></a> Поправила!!!</p>
]]></description><link>https://forum.exlends.ru/post/1177</link><guid isPermaLink="true">https://forum.exlends.ru/post/1177</guid><dc:creator><![CDATA[hannadev]]></dc:creator><pubDate>Wed, 17 Dec 2025 12:49:20 GMT</pubDate></item><item><title><![CDATA[Reply to Как сделать рабочие часы для скрипта on Wed, 17 Dec 2025 12:43:43 GMT]]></title><description><![CDATA[<p dir="auto">можно перезапускать по крону или по pm2 скрипт (pm2 будет каждый  раз перезапускаться после завершения при стандартных настройках)<br />
а проверку  можно сделать еще и в скрипте</p>
<pre><code class="language-js">const now = new Date();
const hour = now.getHours();

if (hour &lt; 8 || hour &gt; 17) {
  process.exit(0);
}

// тут ваша логика
</code></pre>
]]></description><link>https://forum.exlends.ru/post/1176</link><guid isPermaLink="true">https://forum.exlends.ru/post/1176</guid><dc:creator><![CDATA[Mugiwara]]></dc:creator><pubDate>Wed, 17 Dec 2025 12:43:43 GMT</pubDate></item><item><title><![CDATA[Reply to Как сделать рабочие часы для скрипта on Wed, 17 Dec 2025 12:40:25 GMT]]></title><description><![CDATA[<p dir="auto">js это все конечно весело, но каждый инструмент  нужен для своего, вот вариант на crontab, оно будет и легче по ресурсам.</p>
<pre><code class="language-sh">* 8-17 * * * /usr/bin/node /path/to/script.js &gt;&gt; /var/log/myjob.log 2&gt;&amp;1
</code></pre>
]]></description><link>https://forum.exlends.ru/post/1175</link><guid isPermaLink="true">https://forum.exlends.ru/post/1175</guid><dc:creator><![CDATA[Linus]]></dc:creator><pubDate>Wed, 17 Dec 2025 12:40:25 GMT</pubDate></item><item><title><![CDATA[Reply to Как сделать рабочие часы для скрипта on Wed, 17 Dec 2025 12:36:36 GMT]]></title><description><![CDATA[<p dir="auto">и как можно называть переменную, которая отвечает за дату -  <code>data</code>  а не <code>date</code>?</p>
]]></description><link>https://forum.exlends.ru/post/1174</link><guid isPermaLink="true">https://forum.exlends.ru/post/1174</guid><dc:creator><![CDATA[Linus]]></dc:creator><pubDate>Wed, 17 Dec 2025 12:36:36 GMT</pubDate></item><item><title><![CDATA[Reply to Как сделать рабочие часы для скрипта on Wed, 17 Dec 2025 12:33:59 GMT]]></title><description><![CDATA[<p dir="auto">Пользователь <a class="plugin-mentions-user plugin-mentions-a" href="/user/hannadev" aria-label="Profile: hannadev">@<bdi>hannadev</bdi></a> написал в <a href="/post/1150">Как сделать рабочие часы для скрипта</a>:</p>
<blockquote>
<p dir="auto">function workingHours(data = Date ()) {<br />
const hour = data.getHours();<br />
return hour &gt;= 8 &amp;&amp; hour &lt; 17;<br />
}</p>
</blockquote>
<p dir="auto">мне кажется код не рабочий, ты его запускала?  у  data должен быть  новый экземпляр new Date()</p>
]]></description><link>https://forum.exlends.ru/post/1173</link><guid isPermaLink="true">https://forum.exlends.ru/post/1173</guid><dc:creator><![CDATA[Mugiwara]]></dc:creator><pubDate>Wed, 17 Dec 2025 12:33:59 GMT</pubDate></item><item><title><![CDATA[Reply to Как сделать рабочие часы для скрипта on Mon, 15 Dec 2025 06:47:20 GMT]]></title><description><![CDATA[<p dir="auto"><a class="plugin-mentions-user plugin-mentions-a" href="/user/hannadev" aria-label="Profile: hannadev">@<bdi>hannadev</bdi></a> Решение нормальное, но конечно проблема что <code>setInterval()</code> то будет в любом случает в установленное время таску запрашивать.</p>
]]></description><link>https://forum.exlends.ru/post/1156</link><guid isPermaLink="true">https://forum.exlends.ru/post/1156</guid><dc:creator><![CDATA[kirilljsx]]></dc:creator><pubDate>Mon, 15 Dec 2025 06:47:20 GMT</pubDate></item></channel></rss>