制限付きのクロンを無限寿限無にする方法。 #php #無限 #cron

2022.10.12

Logging

おはようございます🦏。昔の文章を読んでくれて今の記事を読まないユーザーさんがいます、凹む😖。

さて、今日はさくらレンタルサーバーでcronを制限以上に使う方法を数年前に書いた記事が未だに読まれたりするのでプログラムコードを直してタイトルも直してQiitaGithubにUPしました。

そのUPした記事があまりアクセスが跳ねなくて少しがっくりしたのがスポーツの日の朝の事です。Qiitaは何だか触りの記事かとても専門性の高い記事が人気を集めるだなって事を、この頃理解したのですが、自分は何方にも寄っていない記事なので跳ねないのかも知れません。

ソースコード貼り付けて置きます。尚、使い方などはQiitaGithubを参照してください。

<?php
date_default_timezone_set('Asia/Tokyo');
class cron
{
    public function __construct(mixed $filepath = "")
    {
        $val = @file_get_contents($this->pval($filepath));
        $obj_ = @json_decode($this->pval($val));
        $obj = (object)[];
        foreach ($obj_ as $key => $value) {
            $obj->name = "month";
            $obj->val = $value->m;
            if ($flg = $this->trigger_check($obj,"m",1,12)) {
                $obj->name = "day";
                $obj->val = $value->d;
                if ($flg = $this->trigger_check($obj,"d",1,31)) {
                    $obj->name = "hour";
                    $obj->val = $value->H;
                    if ($flg = $this->trigger_check($obj,"H",0,23)) {
                        $obj->name = "minutes";
                        $obj->val = $value->i;
                        if ($flg = $this->trigger_check($obj,"i",0,59)) {
                            $obj->name = "week";
                            $obj->val = implode(",", $value->w);
                            if ($flg = $this->trigger_check($obj,"w",0,0)) {
                                $this->command($value->command);
                            }
                        }
                    }
                }
            }
        }
    }
    public function command(mixed $command_val = "")
    {
        $command_val = $this->pval($command_val);
        exec($command_val . " > /dev/null &");
        // print "よろしくお願いします~~~!!".PHP_EOL;
        return true;
    }

    public function pval(mixed $val = "")
    {
        if (is_array($val)) {
            foreach ($val as $key => $value) {
                $val[$key] = strip_tags($value);
            }
        } else {
            $val = strip_tags($val);
        }
        return $val;
    }

    public function trigger_check(mixed $variable = "",mixed $d="",int $min=0 ,int $max=0)
    {
        if (!$variable) return false;
        if ($variable->val === "*") return true;
        switch ($variable->name) {
            case 'week':
                $value = @explode(",", $variable->val);
                return (int)$value[(int)date($d)] === 1 ? true : false;
                break;
            default:
                if (preg_match("/^(\*\/[0-9]{1,})$/", $variable->val)) {
                    $value = @explode("*/", $variable->val)[1];
                    if (is_numeric($value) && $value >= $min && $value <= $max) {
                        return (int)date($d) % $value === 0 ? true : false;
                    }
                }
                if (preg_match("/^([0-9]{1,}\,{1,})/", $variable->val)) {
                    $value = @explode(",", $variable->val);
                    $value = array_map('intval', $value);
                    return in_array((int)date($d), $value, true) === true ? true : false;
                }

                $value = (int)$variable->val;
                if (is_numeric($value) && $value >= $min && $value <= $max) {
                    return $value === (int)date($d) ? true : false;
                }
                return false;
                break;
        }
        return false;
    }
}

if($argv[1]){
    //argv
    new cron($argv[1]);
}


タグ

39, Asia, class, cron, date, default, github, lt, php, public, qiita, set, timezone, Tokyo, UP, アクセス, クロン, コード, サーバー, さくら, スポーツ, ソース, タイトル, プログラム, ユーザー, レンタル, , 人気, , 今日, 何方, 使い方, 制限, 参照, 寿限無, 専門性, 少し, , 文章, 方法, , , , 未だ, 無限, 理解, 自分, 記事, ,

数珠繋ぎのツイートシステムに予約機能を付けました😂 #php #code

2022.10.07

Logging

おはようございます、偏頭痛持ちは雨が降るが一番大変です☔。

先日、数珠繋ぎのツイートシステムを作ったのですが、そのシステムに予約機能を付けました。尚、TwitterAPIのバージョン2でスケジュールのパラメーターが今のところ無いですね。これから先、機能が付くかも知れないですが今のところ無いようです。因みにソースコードは近日中にQiitaGithubにUPします。此処ではソースコードの一部を掲載します(※記事を更新しました下へスクロール🫠)。

Twitter API v2 ツイート数珠繋ぎ

尚、crontabでPHPファイルを叩くようにしています、あと注意事項ですが予約を一度した投稿については変更等は出来ません、編集機能等の機能追加の予定はないです。また、予約管理はsqlite3を使用して管理しています。

<?php
date_default_timezone_set('Asia/Tokyo');
ini_set("display_errors",0);
require_once "./data/tw-config-v2.php";
require_once "../vendor/autoload.php";

use Abraham\TwitterOAuth\TwitterOAuth;

class tw
{
    var $connection = null;
    var $pdo = null;
    function __construct()
    {
        $this->connection = new TwitterOAuth(APIKEY, APISECRET, ACCESSTOKEN, ACCESSTOKENSECRET);
        $this->connection->setApiVersion("2");
    }
    function db_connection()
    {
        try {
            //code...
            $res = $this->pdo = new PDO("sqlite:./data/tw-tweets-db.sqlite3");
        } catch (\Throwable $th) {
            //throw $th;
            //print $th->getMessage();
            $res = false;
        }
        return $res;
    }

    function timecheck($timeonoff, $times)
    {
        if (!$timeonoff) return true;
        $n = new DateTime();
        $t = new DateTime($times);
        return $t <= $n ? true : false;
    }

    function pickup_tweets(mixed $tw_text = null, int $timeonoff = 0, mixed $times = null, string $id = "")
    {
        if (!$times) return false;
        $obj = (object)[];
        $times = preg_replace("/\-/", "/", $times);
        $times = preg_replace("/T/", " ", $times);

        if ($this->timecheck($timeonoff, $times)) {
            if (isset($tw_text) && is_array($tw_text)) {
                foreach ($tw_text as $key => $value) {
                    if (preg_replace("/[ | ]/", "", $value)) {
                        $obj = !$key ? ($this->connection->post("tweets", ["text" => $value], true)
                        ) : ($this->connection->post("tweets", ["reply" => ["in_reply_to_tweet_id" => $obj->data->id], "text" => $value], true)
                        );
                    }
                }
                return true;
            }
        } else {
            return $timeonoff ? $this->save_sqlite($tw_text, $timeonoff, $times, $id): true;
        }
    }

    function save_sqlite($tw_text = null, int $timeonoff = 0, mixed $times = null, string $id = "")
    {
        if ($this->db_connection()) {
            try {
                //code...
                if (isset($tw_text) && is_array($tw_text)) {
                    foreach ($tw_text as $key => &$value) {
                        if (preg_replace("/[ | ]/", "", $value)) {
                            $stmt = $this->pdo->prepare("insert into tweets (tw_id,user,times,tw_text)values(:tw_id,:user,:times,:tw_text)");
                            $stmt->bindValue(":tw_id", $key, PDO::PARAM_INT);
                            $stmt->bindValue(":user", $id, PDO::PARAM_STR);
                            $stmt->bindValue(":times", $times, PDO::PARAM_STR);
                            $stmt->bindValue(":tw_text", $value, PDO::PARAM_STR);
                            $stmt->execute();
                        }
                    }
                }
                $this->pdo = null;
                return true;
            } catch (\Throwable $th) {
                //throw $th;
                return false;
            }
        }
    }
    function tweets_load(string $id = "")
    {
        if (!$id) return false;
        try {
            //code...
            $value = null;
            if ($this->db_connection()) {
                $stmt = $this->pdo->prepare("select * from tweets where user = :user order by times,tw_id asc;");
                $stmt->bindValue(":user", $id, PDO::PARAM_STR);
                $res = $stmt->execute();
                $value = $res ? $stmt->fetchAll() : false;
                $this->pdo = null;
            }
            return $value;            
        } catch (\Throwable $th) {
            //throw $th;
            return false;
        }
    }
    function tweets_update(int $key = 0, int $timeonoff = 0, mixed $times = null, string $id = "",mixed $tw_text="")
    {
        try {
            //code...
            if(!preg_replace("/[ | ]{0,}/","",$tw_text))return false;
            if ($this->db_connection()) {
                $stmt = $this->pdo->prepare("update tweets set tw_text = :tw_text where tw_id = :tw_id and user = :user and times = :times");
                $stmt->bindValue(":tw_id", $key, PDO::PARAM_INT);
                $stmt->bindValue(":user", $id, PDO::PARAM_STR);
                $stmt->bindValue(":times", $times, PDO::PARAM_STR);
                $stmt->bindValue(":tw_text", $tw_text, PDO::PARAM_STR);
                $stmt->execute();
                $this->pdo = null;
            }
        } catch (\Throwable $th) {
            //throw $th;
            return false;
        }
        return true;

    }

    function tweets_delete(int $key = 0, int $timeonoff = 0, mixed $times = null, string $id = "")
    {
        try {
            //code...
            if ($this->db_connection()) {
                $stmt = $this->pdo->prepare("delete from tweets where tw_id = :tw_id and user = :user and times = :times");
                $stmt->bindValue(":tw_id", $key, PDO::PARAM_INT);
                $stmt->bindValue(":user", $id, PDO::PARAM_STR);
                $stmt->bindValue(":times", $times, PDO::PARAM_STR);
                $stmt->execute();
                $this->pdo = null;
            }
        } catch (\Throwable $th) {
            //throw $th;
            return false;
        }
        return true;
    }

    function bat_tweets(mixed $value = null)
    {
        if (!$value) return false;
        $obj = (object)[];
        $t = "";
        foreach ($value as $key => $val) {
            if ($this->timecheck(1, $val["times"])) {
                $obj = ($val["times"]<>$t)? ($this->connection->post("tweets", ["text" => $val["tw_text"]], true)
                ) : ($this->connection->post("tweets", ["reply" => ["in_reply_to_tweet_id" => $obj->data->id], "text" => $val["tw_text"]], true)
                );
                $this->tweets_delete($val["tw_id"], 1, $val["times"], $val["user"]);
                $t = $val["times"];
            } else {
              //  var_dump($val);
              //  break;
            }
        }
    }
}

if ($argv[0]) {
    $tw = new tw();
    $value = $tw->tweets_load(xss_d($argv[1]));
    $tw->bat_tweets($value);
}
function xss_d($val = false)
{
    if (is_array($val)) {
        foreach ($val as $key => $value) {
            $val[$key]  = strip_tags($value);
            $val[$key]  = htmlspecialchars($val[$key]);
        }
    } else {
        $val  = strip_tags($val);
        $val  = htmlspecialchars($val);
    }
    return $val;
}

追記:予約編集機能なども付けました🙄。

GithubとQittaのリンクはこちらです。
Github:https://github.com/taoka-toshiaki/tweets-system-box1
Qitta:https://qiita.com/taoka-toshiaki/items/5ef12b60b267742bf584

タグ

2, , 39, Asia, Code, crontab, date, default, github, ini, lt, php, qiita, Se, set, Sqlite, timezone, Tokyo, TwitterAPI, UP, コード, これ, システム, スクロール, スケジュール, ソース, ツイート, ところ, バージョン, パラメーター, ファイル, 一部, , 予定, 予約, 事項, , 使用, 偏頭痛, , 先日, 変更等, 大変, 投稿, 掲載, 数珠繋ぎ, 更新, 機能, 機能等, 此処, 注意, 管理, 編集, 記事, 近日, 追加, ,

WPのカレンダーや予約投稿の日付がズレてしまう件:WP5.3以降:?

2020.11.15

Logging

WPのカレンダーや予約投稿の日付がズレてしまう件:WP5.3以降に起きるらしい。ワードプレスが大幅なアップグレードしたことが影響しているみたいです。この原因を突き止めるのに結構時間がかかりました。頭の良い人はすごいなと関心、、、。原因ですが簡単に言うとテンプレートやプラグインに下記の関数を使用していたら何やら、日付がズレてしまうというなんとも言えない事象が起きる可能性があります。例えば、テンプレートのFunctions.phpの中にそういう記述があると表示される時にカレンダーがズレてしまうとかそういう現象が発生します。

date_default_timezone_set("Asia/Tokyo");

因みに自分はこの原因を突き止めるのに結構時間を割きました、共通してくれると有り難いです。参考にしたサイトを貼っときます。
https://blog.medical-design.co.jp/archives/2569

元リンクは下記のツイッターのリンクを参照ください。

https://twitter.com/zip358com/status/1327770010404601857

タグ

5.3, Asia, blog, co, date, default, functions, https, jp, medical-design, php, quot, set, timezone, Tokyo, wp, アップ, カレンダー, グレード, こと, サイト, ズレ, テンプレート, なん, プラグイン, プレス, ワード, 下記, , 予約, 事象, , , 使用, 共通, 原因, 参考, 可能性, 大幅, 影響, 投稿, 日付, , 時間, 現象, 発生, 簡単, 自分, 表示, 記述, 関心, 関数, ,

All in One SEO一括、自動入力したった。

2020.07.16

Logging

All in One SEO一括、自動入力したった。そのままです。SEO入力欄にデータを流し込みました。前処理として記事のID番号を列挙してJSONで保存しそのIDデータを使用してSEOタイトル、SEO ディスクリプション、SEO キーワードに記事のタイトル、記事内容、タグをそれぞれ流し込みました。この結果は数ヶ月ぐらいかかると思いますが、良い方向に動いていほしいものです。

ここではJSONデータは記載していませんがプログラム処理から想像出来るかと思います。

<?php
date_default_timezone_set("Asia/Tokyo");
require_once(__DIR__ . '/../wp-load.php');
class db{
    public $db = NULL;
    function __construct()
    {
        $this->db = new PDO('mysql:dbname=DBNAME;host=HOST;charset=utf8;', 'USER', 'PASS');
    }
    public function tbl_update($id,$title,$comment,$keyword){
		//
		$sdb = $this->db->prepare("select * from wp_postmeta where wp_postmeta.post_id = :id and wp_postmeta.meta_key='_aioseop_title';");
		$sdb->bindParam(":id",$id,PDO::PARAM_INT);
		$ret = $sdb->execute();
		var_dump($sdb->rowCount());
		if($sdb->rowCount()){
			$sdb = Null;
			$sdb = $this->db->prepare("UPDATE wp_postmeta set  wp_postmeta.meta_value = :title where wp_postmeta.post_id = :id and wp_postmeta.meta_key='_aioseop_title';");
		}else{
			$sdb = Null;
			$sdb = $this->db->prepare("INSERT INTO wp_postmeta(post_id,meta_key,meta_value) VALUES (:id,'_aioseop_title',:title);");
		}
		$sdb->bindParam(":id",$id,PDO::PARAM_INT);
		$sdb->bindParam(":title",$title,PDO::PARAM_STR);
		$ret = $sdb->execute();
		//
		//
		$sdb = $this->db->prepare("select * from wp_postmeta where wp_postmeta.post_id = :id and wp_postmeta.meta_key='_aioseop_description';");
		$sdb->bindParam(":id",$id,PDO::PARAM_INT);
		$ret = $sdb->execute();
		if($sdb->rowCount()){
			$sdb = Null;
			$sdb = $sdb = $this->db->prepare("UPDATE wp_postmeta set wp_postmeta.meta_value = :comment where wp_postmeta.post_id = :id and wp_postmeta.meta_key='_aioseop_description';");
		}else{
			$sdb = Null;
			$sdb = $this->db->prepare("INSERT INTO wp_postmeta(post_id,meta_key,meta_value) VALUES (:id,'_aioseop_description' ,:comment);");
		}
		$sdb->bindParam(":id",$id,PDO::PARAM_INT);
		$sdb->bindParam(":comment",$comment,PDO::PARAM_STR);
		$ret = $sdb->execute();
		//
		//
		$sdb = $this->db->prepare("select * from wp_postmeta where wp_postmeta.post_id = :id and wp_postmeta.meta_key='_aioseop_keywords';");
		$sdb->bindParam(":id",$id,PDO::PARAM_INT);
		$ret = $sdb->execute();
		if($sdb->rowCount()){
			$sdb = Null;
			$sdb = $this->db->prepare("UPDATE wp_postmeta set wp_postmeta.meta_value = :keyword where wp_postmeta.post_id = :id and wp_postmeta.meta_key='_aioseop_keywords';");
		}else{
			$sdb = Null;
			$sdb = $this->db->prepare("INSERT INTO wp_postmeta(post_id,meta_key,meta_value) VALUES (:id,'_aioseop_keywords' ,:keyword);");
		}
		$sdb->bindParam(":id",$id,PDO::PARAM_INT);
		$sdb->bindParam(":keyword",$keyword,PDO::PARAM_STR);
		$ret = $sdb->execute();
		$sdb = Null;
		$this->db = Null;
        return "{'id':$id,'title':'$title','comment':'$comment','keyword':'$keyword'}";
	}
}
//$_POST["ID"] = 9541;
$obj = (object)json_decode(file_get_contents("./postid.json"));
foreach($obj->rows as $key=>$val){
	$ID = (int)$val->ID;
  $page = get_post($ID);
	$title = mb_strimwidth($page->post_title,0,60,"…");
	$content = $page->post_content;
	$content = wp_strip_all_tags( $content );
	$content = mb_strimwidth(strip_shortcodes( $content ),0,160,"…");
	$keyword = array();
	$posttags = get_the_tags($ID);
	if ( $posttags ) {
	  foreach ( $posttags as $tag ) {
		$keyword[] = $tag->name;
	  }
	}
	$DB = new db();
	print count($keyword)>0?$DB->tbl_update($ID,$title,$content,implode(",",$keyword)):$DB->tbl_update($ID,$title,$content,"");
	$DB = Null;
}

タグ

39, all, Asia, class, construct, date, db, default, DIR, function, ID, in, json, lt, null, once, one, php, public, quot, require, SEO, set, timezone, Tokyo, wp-load, キーワード, ここ, それぞれ, タイトル, タグ, データ, ディスクリプション, プログラム, もの, 一括, 使用, 保存, 入力, 入力欄, 内容, 処理, 列挙, 前処理, 想像, , 方向, 番号, 結果, 自動, 記事, 記載,

bitflyer.comでAPI使ってみたよ、遅っいぞ。

2020.06.05

Logging

bitflyer.comでAPI使ってみたよ、遅っいぞ。自分の回線が悪いのかわからないけれど、データの結果が返却されるまで2?4分ぐらい時間がかかるのです、レスポンスが遅い恐ろしく遅いのだ。
まるでオイラのようだ(´・ω・`)。

ccxtとかも使ってみたら・・アレ大丈夫?
PHPで再度を自作してみた「body部分は間違っているかも。いや間違っているよ・・・?。」とぶつぶつ言いながら制作。

追記:
PHPのレスポンスが遅いのは、LinuxのOSをゴニョゴニョしたからでした。OS入れ直して再度コードを走らすと普通にレスポンスが返ってきました、、、。

返ってきたときには「ほんと、何やねん」とボヤきました?。

PHPのソースコードを記載します。

<?php
date_default_timezone_set('Asia/Tokyo');
class Api_Bitflyer_Class
{
    var $basic_url = "https://api.bitflyer.com";
    public function __construct()
    {
        require_once __DIR__."/../common/init.php";
    }
    /**
     * @param timestamp $timestamp
     * @param string $path
     * @param string $method
     * @param string $body
     */  
    public function api_set($timestamp = "", $path = "/v1/me/getbalance", $method = "GET", $body = "")
    {
        $url = $this->basic_url . $path;
        $data = strtolower($method) === "get" ? $timestamp . $method . $path : $timestamp . $method . $path . (function ($body) {
            if (!is_array($body)) {
                $body = [];
            }
            return json_encode($body);
        })($body);
        $access_singn = hash_hmac("sha256", $data, APISECRET);
        $headers = [
            'ACCESS-KEY: ' . APIKEY,
            'ACCESS-TIMESTAMP: ' . $timestamp,
            'ACCESS-SIGN: ' . $access_singn,
            'Content-Type: application/json',
        ];
        return new class($url, $method, $headers, $body)
        {
            var $url = "";
            var $method = "";
            var $headers = "";
            var $body = "";
            /**
             * @param string $url
             * @param string $method
             * @param string $headers
             * @param string $body
             */              
            public function __construct($url, $method, $headers, $body)
            {
                $this->url = $url;
                $this->method = $method;
                $this->headers = $headers;
                $this->body = $body;
            }
            public function api_run()
            {
                $curl = curl_init();
                curl_setopt($curl, CURLOPT_URL, $this->url);
                curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $this->method);
                curl_setopt($curl, CURLOPT_HTTPHEADER, $this->headers);
                strtolower($this->method) == "post" ? curl_setopt($curl, CURLOPT_POSTFIELDS, $this->body) : "";
                curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
                curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
                $response             = curl_exec($curl);
                // $response_info        = curl_getinfo($curl);
                // $response_code        = $response_info['http_code'];
                // $response_header_size = $response_info['header_size'];
                curl_close($curl);
                print date("Y/m/d H:i:s");
                var_dump(json_decode($response));
                // var_dump($response_code);
                // var_dump($response_header_size);
            }
        };
    }
}

$Api_Bitflyer_Class = new Api_Bitflyer_Class();
$Api_Bitflyer_Class->api_set(time(),"/v1/me/getbalance","GET","")->api_run();

PHPとは別にnode.jsでリアルタイムAPIを使用した動画を貼っときます。

bitflyerAPI_PHPcode

なお、よく読んだほうが良いAPI Documentation

bitFlyer Lightning では、HTTP API と Realtime API の 2 種類の API を提供しています。

尚、ビットコイン高くて買えないので、ビットコインの売買したい知人は格安で自動売買のシステム作りますよ。

タグ

2, 39, 4, API, Asia, bitFlyer, body, ccxt, class, com, date, default, Linux, lt, OS, php, set, timezone, Tokyo, アレ, おいら, コード, ゴニョゴニョ, ソース, データ, とき, ほんと, レスポンス, , 再度, 制作, 回線, 時間, 普通, 結果, 自作, 自分, 記載, 返却, 追記, , 部分,

月の満ち欠けPHPライブラリを書きました。ちょっと適当なアイコンで表示。

2020.02.22

Logging

月の満ち欠けPHPライブラリを書きました、ご自由にお使いください。

ちょっと適当なアイコンで表示。
もっと正確なアイコンを取り入れたい方はご自身でご自由に変更ください。
月の満ち欠けの計算方法はネットから見つけてきました。
情報を記載していただいた先人の知恵を借りPHPライブラリが出来ました。
ありがとうございます。

<?php
//date_default_timezone_set('Asia/Tokyo');
class moon{
    static public $icon = array(
        "0"=>'?',//朔
        "1"=>'?',//朔
        "2"=>'?',//朔
        "3"=>'?',//三日月
        "4"=>'?',//三日月
        "5"=>'?',//三日月
        "6"=>'?',//三日月
        "7"=>'?',//上弦の月',
        "8"=>'?',//上弦の月',
        "9"=>'?',//上弦の月',
        "10"=>'?',//上弦の月',
        "11"=>'?',//上弦の月',
        "12"=>'?',//十三夜月
        "13"=>'?',//十三夜月
        "14"=>'?',//十三夜月
        "15"=>"?",//望月
        "16"=>"?",//望月
        "17"=>"?",//望月
        "18"=>"?",//望月
        "19"=>"?",//寝待月
        "20"=>"?",//寝待月
        "21"=>"?",//寝待月
        "22"=>"?",//寝待月
        "23"=>'?',//下弦の月
        "24"=>'?',//下弦の月
        "25"=>'?',//下弦の月
        "26"=>"?",//二十六夜月
        "27"=>"?",//二十六夜月
        "28"=>"?",//二十六夜月
        "29"=>"?"//二十六夜月
    );
    static public $res = "0";
    static public $moon_gregorian = array(0,2,0,2,2,4,5,6,7,8,9,10);
    public function main($year=2012,$mon=12,$day=12)
    {
        static::$res = ((($year-11)%19)*11 + static::$moon_gregorian[$mon-1]+$day)%30;
    }
    public function icon(){
        return static::$icon[static::$res];
    }
}

呼び出しはこんな感じで。

<?php
    moon::main($year,$mon,$day);
    $chg = moon::icon();

タグ

0, , 2, , 39, array, Asia, class, date, default, gt, icon, lt, moon, php, public, quot, set, static, timezone, Tokyo, アイコン, ご自身, ネット, ライブラリ, 先人, 変更, 情報, , 方法, , , 正確, 満ち欠け, 知恵, 表示, 計算, 記載, 適当,

さくらレンタルサーバーとかで制限以上のクロンタブ(crontab)を使う方法。

2018.11.08

Logging

さくらレンタルサーバーとかで制限以上のクロンタブ(crontab)を使う方法
10年ぐらいまえのコードを見直して改善したコードが下記になります。
10年前はクラスを使わない方法で構築したのだけど、今回はクラスの概念を
使って構築。ここ何年かで自分のコーディングの技術は上がっているかといえば
そうでもないですが、昔よりかは技術の幅は広がっていると思いたいw
※qiita日付は数年前にUPしたのですけど、コード自体は10年前のコードです。

追記:2022/10/08 修正:詳しくはコチラ
https://qiita.com/question909/items/8f1df9b62ab4fba76243

<?php
//5分刻みに対して有効な無限クローン 処理が負荷の場合どうなるかは知りません。
date_default_timezone_set('Asia/Tokyo');
class cron{

    public function d_m($obj)
    {
            if($obj->m==="*")return true;
            if(preg_match("/,/",$obj->m))return $this->comma($obj->m,date("m"));
            if((int)$obj->m === (int)date("m"))return true;

            return false;
    }

    public function d_d($obj)
    {
            if($obj->d==="*")return true;
            if(preg_match("/,/",$obj->d))return $this->comma($obj->d,date("d"));
            if((int)$obj->d === (int)date("d"))return true;

            return false;
    }

    public function d_H($obj)
    {
            if(preg_match("/\*\/[0-9]{1,2}/",$obj->H)){
                $H = explode("/",$obj->H);
                if((int)$H[1]>0 && ((int)date("H") % (int)$H[1])===0)return true;
            }else{
                if($obj->H==="*")return true;
                if(preg_match("/,/",$obj->H))return $this->comma($obj->H,date("H"));
                if((int)$obj->H === (int)date("H"))return true;

            }
            return false;
    }

    public function d_i($obj)
    {
            if(preg_match("/\*\/[0-9]{1,2}/",$obj->i)){
                $i = explode("/",$obj->i);
                if((int)$i[1]>0 && ((int)date("i") % (int)$i[1])===0)return true;
            }else{
                if($obj->i==="*")return true;
                if(preg_match("/,/",$obj->i))return $this->comma($obj->i,date("i"));
                if((int)$obj->i === (int)date("i"))return true;

            }
            return false;
    }

    //曜日 0=日曜日 6=土曜日
    public function d_w($obj)
    {
            if((int)$obj->w[date("w")]===1)return true;
            return false;
    }

    public  function comma($c="",$t=""){
        if($c==="")return false;
        if($t==="")return false;
        $flg = false;
        foreach(explode(",",$c) as $cc){
            if((int)$cc===(int)$t)$flg = true;
        }
        return $flg;
    }


    public function d_command($obj){
        if($obj->command){
            exec($obj->command . " > /dev/null &");
        }
        return true;
    }

}
if ($argv[1]) {
   $filename = $argv[1];
    if(is_file($filename)){
        $jsn = json_decode(file_get_contents($filename));
        $cron = new cron();
        try {
            foreach($jsn as $obj){
                if($cron->d_m($obj)){
                    if($cron->d_d($obj)){
                        if($cron->d_H($obj)){
                            if($cron->d_i($obj)){
                                if($cron->d_w($obj)){
                                    $cron->d_command($obj);//波動拳{{{{
                                }
                            }
                        }
                    }
                }
            }
        } catch (\Throwable $th) {
            print $th->getMessage();
        }
    }
}

タグ

08, 10, 2022, 39, 5, Asia, class, cron, crontab, date, default, function, if, lt, obj, php, public, qiita, set, timezone, Tokyo, UP, , クラス, クローン, クロン, コーディング, コード, ここ, コチラ, サーバー, さくら, タブ, まえ, レンタル, 下記, 今回, 何年か, 修正, 処理, 分刻み, 制限, 場合, , 技術, 改善, , 方法, 日付, , 有効, 概念, 構築, 無限, 自体, 自分, 負荷, 追記,

昨日の続き、cronPHP(´Д`)、一つのジョブから複数のPHPファイルを実行させる方法。

2015.06.25

Logging

<?php
//5分刻みに対して有効な無限クローン 処理が負荷の場合どうなるかは知りません。
date_default_timezone_set('Asia/Tokyo');
class cron{

    public function d_m($obj)
    {
            if($obj->m==="*")return true;
            if(preg_match("/,/",$obj->m))return $this->comma($obj->m,date("m"));
            if((int)$obj->m === (int)date("m"))return true;

            return false;
    }

    public function d_d($obj)
    {
            if($obj->d==="*")return true;
            if(preg_match("/,/",$obj->d))return $this->comma($obj->d,date("d"));
            if((int)$obj->d === (int)date("d"))return true;

            return false;
    }

    public function d_H($obj)
    {
            if(preg_match("/\*\/[0-9]{1,2}/",$obj->H)){
                $H = explode("/",$obj->H);
                if((int)$H[1]>0 && ((int)date("H") % (int)$H[1])===0)return true;
            }else{
                if($obj->H==="*")return true;
                if(preg_match("/,/",$obj->H))return $this->comma($obj->H,date("H"));
                if((int)$obj->H === (int)date("H"))return true;

            }
            return false;
    }

    public function d_i($obj)
    {
            if(preg_match("/\*\/[0-9]{1,2}/",$obj->i)){
                $i = explode("/",$obj->i);
                if((int)$i[1]>0 && ((int)date("i") % (int)$i[1])===0)return true;
            }else{
                if($obj->i==="*")return true;
                if(preg_match("/,/",$obj->i))return $this->comma($obj->i,date("i"));
                if((int)$obj->i === (int)date("i"))return true;

            }
            return false;
    }

    //曜日 0=日曜日 6=土曜日
    public function d_w($obj)
    {
            if((int)$obj->w[date("w")]===1)return true;
            return false;
    }

    public  function comma($c="",$t=""){
        if($c==="")return false;
        if($t==="")return false;
        $flg = false;
        foreach(explode(",",$c) as $cc){
            if((int)$cc===(int)$t)$flg = true;
        }
        return $flg;
    }


    public function d_command($obj){
        if($obj->command){
            exec($obj->command . " > /dev/null &");
        }
        return true;
    }

}
if ($argv[1]) {
   $filename = $argv[1];
    if(is_file($filename)){
        $jsn = json_decode(file_get_contents($filename));
        $cron = new cron();
        try {
            foreach($jsn as $obj){
                if($cron->d_m($obj)){
                    if($cron->d_d($obj)){
                        if($cron->d_H($obj)){
                            if($cron->d_i($obj)){
                                if($cron->d_w($obj)){
                                    $cron->d_command($obj);//波動拳{{{{
                                }
                            }
                        }
                    }
                }
            }
        } catch (\Throwable $th) {
            print $th->getMessage();
        }
    }
}

 
この頃、ネタがないので手抜き投稿です。気づいた人どのぐらいいるのだろうか?
Qittaに公開しました。https://qiita.com/question909/items/8f1df9b62ab4fba76243

タグ

39, 5, Asia, class, comma, cron, cronphp, date, default, function, gt, if, int, lt, match, obj, php, preg, public, quot, retu, return, set, this, timezone, Tokyo, true, クローン, ジョブ, ファイル, 一つ, 処理, 分刻み, 場合, 実行, 方法, 昨日, 有効, 無限, 複数, 負荷,

cronPHPを作ってみた朝の続き。

2015.06.24

Logging


 
cronPHPを作ってみた朝の続き・・・たぶん、コレだけで十分かと思います(稼働させてないのでどう動くかは不明?)。仕事帰って作りました。この頃、もっと勉強しないとなと思うこの頃です。いまの自分に足りないのは間違いなく技術力です、あとタイピングとか・・・かなり遅いので生産性がかなり低いです。英語を打つのに遅すぎる・・・・。日本語はまぁまぁ早いのですけど。キーを覚えているというよりは何となく覚えているので・・・・なぜ、タイピングできるのか自分でも不思議なのです。
 

追記2022/09/06:詳しくは、こちらを参照くださいませ

<?php
//5分刻みに対して有効な無限クローン 処理が負荷の場合どうなるかは知りません。
date_default_timezone_set('Asia/Tokyo');
class cron{

    public function d_m($obj)
    {
            if($obj->m==="*")return true;
            if(preg_match("/,/",$obj->m))return $this->comma($obj->m,date("m"));
            if((int)$obj->m === (int)date("m"))return true;

            return false;
    }

    public function d_d($obj)
    {
            if($obj->d==="*")return true;
            if(preg_match("/,/",$obj->d))return $this->comma($obj->d,date("d"));
            if((int)$obj->d === (int)date("d"))return true;

            return false;
    }

    public function d_H($obj)
    {
            if(preg_match("/\*\/[0-9]{1,2}/",$obj->H)){
                $H = explode("/",$obj->H);
                if((int)$H[1]>0 && ((int)date("H") % (int)$H[1])===0)return true;
            }else{
                if($obj->H==="*")return true;
                if(preg_match("/,/",$obj->H))return $this->comma($obj->H,date("H"));
                if((int)$obj->H === (int)date("H"))return true;

            }
            return false;
    }

    public function d_i($obj)
    {
            if(preg_match("/\*\/[0-9]{1,2}/",$obj->i)){
                $i = explode("/",$obj->i);
                if((int)$i[1]>0 && ((int)date("i") % (int)$i[1])===0)return true;
            }else{
                if($obj->i==="*")return true;
                if(preg_match("/,/",$obj->i))return $this->comma($obj->i,date("i"));
                if((int)$obj->i === (int)date("i"))return true;

            }
            return false;
    }

    //曜日 0=日曜日 6=土曜日
    public function d_w($obj)
    {
            if((int)$obj->w[date("w")]===1)return true;
            return false;
    }

    public  function comma($c="",$t=""){
        if($c==="")return false;
        if($t==="")return false;
        $flg = false;
        foreach(explode(",",$c) as $cc){
            if((int)$cc===(int)$t)$flg = true;
        }
        return $flg;
    }


    public function d_command($obj){
        if($obj->command){
            exec($obj->command . " > /dev/null &");
        }
        return true;
    }

}
if ($argv[1]) {
   $filename = $argv[1];
    if(is_file($filename)){
        $jsn = json_decode(file_get_contents($filename));
        $cron = new cron();
        try {
            foreach($jsn as $obj){
                if($cron->d_m($obj)){
                    if($cron->d_d($obj)){
                        if($cron->d_H($obj)){
                            if($cron->d_i($obj)){
                                if($cron->d_w($obj)){
                                    $cron->d_command($obj);//波動拳{{{{
                                }
                            }
                        }
                    }
                }
            }
        } catch (\Throwable $th) {
            print $th->getMessage();
        }
    }
}

タグ

06, 09, 2022, 39, 5, Asia, class, cron, cronphp, date, default, function, lt, nbsp, obj, php, public, set, timezone, Tokyo, いま, かなり, キー, クローン, こちら, コレ, ダイビング, 不思議, 不明, 仕事, 処理, 分刻み, 勉強, 参照, 場合, 技術力, 日本語, 有効, , 無限, 生産性, 稼働, 自分, 英語, 負荷, 追記, ,

cronの設定数に制限があるさくらサーバーとかで制限以上に使う方法(´Д`)

2015.01.12

Logging

cronの設定数に制限があるさくらサーバーとかで制限数以上(cron設定を増やす方法
)に使う方法はないかなと考えた結果、自分はこうしました。
一つのPHPファイル(実行ファイル)から複数のファイルをキックすることに!(´Д`)
こうすれば、処理が遅くないファイルなら複数個でも実行できるのではないかと
思ったわけです。結果的に成功しているぽっいです。
※Shellで作れる人は作れるだろうけど自分には無理(´∀`*)ポッいのでPHPで制作しました。
ちなみにさくらレンタルサーバーの場合、php.iniにタイムゾーン設定を
加えてあげてください(date.timezone = Asia/Tokyo ←追加)。
そうしないと動かない恐れがあります。
作っていて思ったことですが、作る考え方はわかるものの、元々メソッドを覚えていない
人間なのでググってメソッド探しにまずヘタりました( ´Д`)=3。その後、完璧なハズとか
思ってソースを実行させるとエラーは出ないものの。思った通りうごかないという事象に
苦しめられること2時間、何でだろうとか思っていて検証してみた結果、メソッドの使い方が
間違っていたり、変数名が間違っていたりとなんとも言えない無情さに襲われましたが
何とか動作するようになったみたいなのでコードをうっぷします。
ソースコードを記載しときます。動作するとは
思いますが誤作動するかもしれないので保証はしません。なお、いつもながら
ソースにはコメントを記載しておりませんのでトレースしてください。
PHPファイルのDLはこちらから( ´Д`)=3?(最終更新日2015/01/12 11:07)
追記2
改良しました。{*改良版はこちら*}
※このPHPファイルを5分置きにキックしていますΣ(゚∀´(┗┐ヽ(・∀・ )ノ。

<?php
//5分刻みに対して有効な無限クローン 処理が負荷の場合どうなるかは知りません。
date_default_timezone_set('Asia/Tokyo');
class cron{

    public function d_m($obj)
    {
            if($obj->m==="*")return true;
            if(preg_match("/,/",$obj->m))return $this->comma($obj->m,date("m"));
            if((int)$obj->m === (int)date("m"))return true;

            return false;
    }

    public function d_d($obj)
    {
            if($obj->d==="*")return true;
            if(preg_match("/,/",$obj->d))return $this->comma($obj->d,date("d"));
            if((int)$obj->d === (int)date("d"))return true;

            return false;
    }

    public function d_H($obj)
    {
            if(preg_match("/\*\/[0-9]{1,2}/",$obj->H)){
                $H = explode("/",$obj->H);
                if((int)$H[1]>0 && ((int)date("H") % (int)$H[1])===0)return true;
            }else{
                if($obj->H==="*")return true;
                if(preg_match("/,/",$obj->H))return $this->comma($obj->H,date("H"));
                if((int)$obj->H === (int)date("H"))return true;

            }
            return false;
    }

    public function d_i($obj)
    {
            if(preg_match("/\*\/[0-9]{1,2}/",$obj->i)){
                $i = explode("/",$obj->i);
                if((int)$i[1]>0 && ((int)date("i") % (int)$i[1])===0)return true;
            }else{
                if($obj->i==="*")return true;
                if(preg_match("/,/",$obj->i))return $this->comma($obj->i,date("i"));
                if((int)$obj->i === (int)date("i"))return true;

            }
            return false;
    }

    //曜日 0=日曜日 6=土曜日
    public function d_w($obj)
    {
            if((int)$obj->w[date("w")]===1)return true;
            return false;
    }

    public  function comma($c="",$t=""){
        if($c==="")return false;
        if($t==="")return false;
        $flg = false;
        foreach(explode(",",$c) as $cc){
            if((int)$cc===(int)$t)$flg = true;
        }
        return $flg;
    }


    public function d_command($obj){
        if($obj->command){
            exec($obj->command . " > /dev/null &");
        }
        return true;
    }

}
if ($argv[1]) {
   $filename = $argv[1];
    if(is_file($filename)){
        $jsn = json_decode(file_get_contents($filename));
        $cron = new cron();
        try {
            foreach($jsn as $obj){
                if($cron->d_m($obj)){
                    if($cron->d_d($obj)){
                        if($cron->d_H($obj)){
                            if($cron->d_i($obj)){
                                if($cron->d_w($obj)){
                                    $cron->d_command($obj);//波動拳{{{{
                                }
                            }
                        }
                    }
                }
            }
        } catch (\Throwable $th) {
            print $th->getMessage();
        }
    }
}

タグ

, Asia, cron, date, ini, php, shell, timezone, Tokyo, いの, キック, こと, サーバー, さくら, ゾーン, タイム, パス, ファイル, ヘタ, ボツ, メソッド, レンタル, わけ, 一つ, , 人間, 処理, 制作, 制限, 場合, 完璧, 実行, , 成功, 方法, 無理, 結果, 考え方, 自分, 複数, 複数個, 設定, 追加,